Java Code for Newton's Method

5.2 Java Code for Newton's Method

Below is a copy of the code for our Newton's method solver. You can continue with the tutorial by clicking the correct navigation button, or you can jump to the part of the tutorial that describes a part of the program that you are interested in by clicking on the relevant section of code below. We will continue the tutorial by looking at how to compile and run this code..
class Newton  {

    static double f(double x) {
	return Math.sin(x);

    static double fprime(double x) {
        return Math.cos(x);

    public static void main(String argv[]) {

	  double tolerance = .000000001; // Our approximation of zero
	  int max_count = 200; // Maximum number of Newton's method iterations

/* x is our current guess. If no command line guess is given, 
   we take 0 as our starting point. */

	  double x = 0;

	  if(argv.length==1) {
	    x= Double.valueOf(argv[0]).doubleValue();

         for( int count=1;
                  (Math.abs(f(x)) > tolerance) && ( count < max_count);
                 count ++)  {
            x= x - f(x)/fprime(x);
	    System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));

	  if( Math.abs(f(x)) <= tolerance) {
	   System.out.println("Zero found at x="+x);
	  else {
	   System.out.println("Failed to find a zero");

Next 5.3 Compiling and Running the Newton Class

David Maxwell, who is still writing this, would like to hear your comments and suggestions.