Example: Regression with User-supplied Basis Functions

In this example, we fit the function 1 + sin(x) + 7 * sin(3x) with no error introduced. The function is evaluated at 90 equally spaced points on the interval [0, 6]. Four basis functions are used, sin(kx) for k = 1,...,4 with no intercept.
import com.imsl.stat.*;
import com.imsl.math.*;

public class UserBasisRegressionEx1 {
    public static void main(String args[]) {
        class Basis1 implements RegressionBasis {
            public double basis(int index, double x) {
                return Math.sin((index+1)*x);
            }
        }
        
        double coef[] = new double[4];
        UserBasisRegression ubr = 
        new UserBasisRegression(new Basis1(), 4, false);
        
        for (int k = 0;  k < 90;  k++) {
            double x = 6.0*k/89.0;
            double y = 1.0 + Math.sin(x) + 7.0*Math.sin(3.0*x);
            ubr.update(x, y, 1.0);
        }
        coef = ubr.getCoefficients();
        new PrintMatrix("The regression coefficients are:").print(coef);
    }
}

Output

The regression coefficients are:
     0    
0  1.01   
1  0.02   
2  7.029  
3  0.037  

Link to Java source.