Example 1: Nonlinear Regression using Finite Differences

In this example a nonlinear model is fitted. The derivatives are obtained by finite differences.
import com.imsl.stat.*;
import com.imsl.math.*;

public class NonlinearRegressionEx1 {
    public static void main(String args[])
        throws NonlinearRegression.TooManyIterationsException, 
        NonlinearRegression.NegativeFreqException, 
        NonlinearRegression.NegativeWeightException {
        NonlinearRegression.Function f = new NonlinearRegression.Function() {

            public boolean f(double theta[], int iobs, double frq[],
               double wt[], double e[]){

                double ydata[] = {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[] = {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};
                boolean 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;
            }
        };

        int nparm = 2;
        double theta[] = {60.0, -0.03};
        NonlinearRegression regression = new NonlinearRegression(nparm);
        regression.setGuess(theta);     
        double coef[] = regression.solve(f);
        System.out.println("The computed regression coefficients are {" +
            coef[0] + ", " + coef[1] + "}");
        int rank = regression.getRank();
        System.out.println("The computed rank is "+rank);
        double dfe = regression.getDFError();
        System.out.println("The degrees of freedom for error are "+dfe);
        double sse = regression.getSSE();
        System.out.println("The sums of squares for error is "+sse);
        double r[][] = regression.getR();
        new PrintMatrix("R from the QR decomposition ").print(r);
    }
}

Output

The computed regression coefficients are {58.606562944502656, -0.0395864473118334}
The computed rank is 2
The degrees of freedom for error are 13.0
The sums of squares for error is 49.45929986247174
R from the QR decomposition 
     0        1      
0  1.874  1,139.928  
1  0      1,139.798  

Link to Java source.