In this example a nonlinear model is fitted. The derivatives are supplied by the user.
using System; using Imsl.Math; using Imsl.Stat; public class NonlinearRegressionEx2 : NonlinearRegression.IDerivative { double[] ydata = new double[]{ 54.0, 50.0, 45.0, 37.0, 35.0, 25.0, 20.0, 16.0, 18.0, 13.0, 8.0, 11.0, 8.0, 4.0, 6.0}; 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; public bool f(double[] theta, int iobs, double[] frq, double[] wt, double[] e) { 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 bool derivative(double[] theta, int iobs, double[] frq, double[] wt, double[] de) { if (iobs < nobs) { wt[0] = 1.0; frq[0] = 1.0; iend = true; de[0] = - Math.Exp(theta[1] * xdata[iobs]); de[1] = (- theta[0]) * xdata[iobs] * Math.Exp(theta[1] * xdata[iobs]); } else { iend = false; } return iend; } public static void Main(String[] args) { int nparm = 2; double[] theta = new double[]{60.0, - 0.03}; NonlinearRegression regression = new NonlinearRegression(nparm); regression.Guess = theta; double[] coef = regression.Solve(new NonlinearRegressionEx2()); 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 {58.6065629254192, -0.0395864472775247} The computed rank is 2 The degrees of freedom for error are 13 The sums of squares for error is 49.4592998624722 R from the QR decomposition 0 1 0 1.87385998422826 1139.92837730064 1 0 1139.79757620697Link to C# source.