Implementation of Newton Method written in Java.

IN
-3
0.0000001
OUT
X: -3.0 f(x): 2.0
X: -2.5 f(x): 0.25
X: -2.4166666666666665 f(x): 0.006944444444443976
X: -2.4142156862745097 f(x): 6.007304882427178E-6
import java.util.Scanner;

// © 2018 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net
public class Main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        double prevX;
        double x;
        double precision;

        System.out.print("Enter initial guess: ");
        x = reader.nextDouble();

        prevX = x;

        System.out.print("Enter precision of method: ");
        precision = reader.nextDouble();

        while(Math.abs(function(x)) > precision){
            System.out.println("X: " + x + " f(x): " + function(x));

            x = prevX - (function(prevX) / functionDerivative(prevX));
            prevX = x;
        }
    }

    private static double function(double x) { //x^2 + 2x - 1
        return x * (x + 2) - 1;
    }

    private static double functionDerivative(double x) { //x^2 + 2x - 1
        return 2 * x + 2;
    }
}

 



Java Newton Method
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close