Newton's Method Java

user2809115 picture user2809115 · Oct 9, 2013 · Viewed 9.6k times · Source

Currently I am creating (trying) a program for Newton's Method and its suppose to allow you to guess the initial root and give you the roots. But I can't figure out how to put the x1=x0-f(x0)/f(x0) also needs a loop Here's my code currently :

import java.util.Scanner;

public class NewtonsMethod {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter your guess for the root:");
        double x = keyboard.nextDouble();
        double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
            for(x=x-f(x)/f(x));

        System.out.println("Your answer is:" + guessRootAnswer);

    }
}

Answer

Johan picture Johan · Oct 9, 2013

You've misstated how newton's method works:

The correct formula is:

xn+1 <= xn-f(xn)/f '(xn)

Note that the second function is the first order derivative of the first one.
How the first order derivative looks depends on the exact nature of the function.

If you know what f(x) looks like, when you code the program, you can also fill in the code for the first derivative. If you have to figure it out at runtime, it looks like much more or a massive undertaking.

The following code from: http://www.ugrad.math.ubc.ca/Flat/newton-code.html
demonstrates the concept:

class Newton  {

    //our functio f(x)
    static double f(double x) {
        return Math.sin(x);
    }

    //f'(x) /*first derivative*/
    static double fprime(double x) {
        return Math.cos(x);
    }

    public static void main(String argv[]) {

        double tolerance = .000000001; // Stop if you're close enough
        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;
            //Carry on till we're close, or we've run it 200 times.
            (Math.abs(f(x)) > tolerance) && ( count < max_count); 
             count ++)  {

            x= x - f(x)/fprime(x);  //Newtons method.
            System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
        }     
        //OK, done let's report on the outcomes.       
        if( Math.abs(f(x)) <= tolerance) {
            System.out.println("Zero found at x="+x);
        } else {
            System.out.println("Failed to find a zero");
        }
    }   
}