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