Introduction to Interfaces through functions
Given a differentiable function, Newton's method gives us a method to take an approximation to a root and find a better aproximation. Suppose we only want to write code to do Newton's method once, but we want to be able to apply our code to any function.

The solution is to create an interface to represent the types of function we want to deal with.


The Interface: (Function.java)
/** Any class that implements this interface will represent a differentiable function
 * from R to R. */
public interface Function {
    /** Evaluate the function at x. */
    public double eval(double x);
    /** Evaluate the derivative of the function at x. */
    public double d(double x);
}

Now we can write a class to take a function and do Newton's Method. Here is the barebones of Newton's Method:

Newton's Method: (NewtonsMethod.java)
public class NewtonsMethod {
    // the function we want to find a root of 
    Function f;
    // the current approximation of the root
    double x;
    
    /** start should be an approximation of a root of the function f */
    public NewtonsMethod(Function f, double start) {
        this.f=f;
        this.x=start;
    }

    /** do one interation of Newton's method to improve the approximation */
    public void iterate() {
        x= x - f.eval(x)/f.d(x);
    }    
}

We also need to know how to build functions to apply Newton's Method to.

The Sine Function: (Sine.java)
/** The sine function */
public class Sine implements Function {
    public Sine() {}
    public double eval(double x){
        return Math.sin(x);
    }
    public double d(double x){
        return Math.cos(x);
    }
}

Quadratic Functions: (Quadratic.java)
/** Any quadratic function */
public class Quadratic implements Function {
    double a,b,c;
    /** Construct the quadratic function a x^2 + b x + c */
    public Quadratic(double a, double b, double c) {
	this.a=a;
	this.b=b;
	this.c=c;
    }
    public double eval(double x){
        return a*x*x+b*x+c;
    }
    public double d(double x){
        return 2*a*x+b;
    }
}

The Product of two Functions: (ProductFunction.java)
/** The product of two function */
public class ProductFunction implements Function {
    Function f, g;
    public ProductFunction(Function f, Function g) {
	this.f=f;
	this.g=g;
    }
    /** evaluates the product */
    public double eval(double x){
        return f.eval(x)*g.eval(x);
    }
    /** evaluates the derivative using the chain rule */
    public double d(double x){
        return f.eval(x)*g.d(x)+f.d(x)*g.eval(x);
    }
}

Download the whole source [all.tar.gz]

HOME >>>>> PROGRAMMING >>>>> JAVA >>>>> EXAMPLES