In this example, some nondefault tolerances and scales are used to fit a nonlinear model. The data is 1.e-10 times the data of Example 1. In order to fit this model without rescaling the data, we first set the absolute function tolerance to 0.0. The default value would cause the program to terminate after one iteration because the residual sum of squares is roughly 1.e-19. We also set the relative function tolerance to 0.0. The gradient tolerance is properly scaled for this problem so we leave it at its default value. Finally, we set the elements of scale to the absolute value of the recipricol of the starting value. The derivatives are obtained by finite differences.
using System; using Imsl.Math; using Imsl.Stat; public class NonlinearRegressionEx3 : NonlinearRegression.IFunction { public bool f(double[] theta, int iobs, double[] frq, double[] wt, double[] e) { double[] ydata = new double[]{ 54e-10, 50e-10, 45e-10, 37e-10, 35e-10, 25e-10, 20e-10, 16e-10, 18e-10, 13e-10, 8e-10, 11e-10, 8e-10, 4e-10, 6e-10}; double[] xdata = new double[]{ 2.0, 5.0, 7.0, 10.0, 14.0, 19.0, 26.0, 31.0, 34.0, 38.0, 45.0, 52.0, 53.0, 60.0, 65.0}; bool iend; int nobs = 15; if (iobs < nobs) { wt[0] = 1.0; frq[0] = 1.0; iend = true; e[0] = ydata[iobs] - theta[0] * Math.Exp(theta[1] * xdata[iobs]); } else { iend = false; } return iend; } public static void Main(String[] args) { int nparm = 2; double[] theta = new double[]{6e-9, - 0.03}; double[] scale = new double[nparm]; NonlinearRegression regression = new NonlinearRegression(nparm); regression.Guess = theta; regression.AbsoluteTolerance = 0.0; regression.RelativeTolerance = 0.0; scale[0] = 1.0 / Math.Abs(theta[0]); scale[1] = 1.0 / Math.Abs(theta[1]); regression.Scale = scale; NonlinearRegression.IFunction fcn = new NonlinearRegressionEx3(); double[] coef = regression.Solve(fcn); Console.Out.WriteLine("The computed regression coefficients are {" + coef[0] + ", " + coef[1] + "}"); Console.Out.WriteLine("The computed rank is " + regression.Rank); Console.Out.WriteLine("The degrees of freedom for error are " + regression.DFError); Console.Out.WriteLine("The sums of squares for error is " + regression.GetSSE()); new PrintMatrix("R from the QR decomposition ").Print(regression.R); } }
The computed regression coefficients are {5.78378362045064E-09, -0.0396252538454606} The computed rank is 2 The degrees of freedom for error are 13 The sums of squares for error is 5.1663766194061E-19 R from the QR decomposition 0 1 0 1.87310563181707 5.74734586570442E-09 1 0 5.83713991871454E-11Link to C# source.