/* From: "COMPUTATIONAL PHYSICS, 2nd Ed" by RH Landau, MJ Paez, and CC Bordeianu Copyright Wiley-VCH, 2007. Electronic Materials copyright: R Landau, Oregon State Univ, 2007; MJ Paez, Univ Antioquia, 2007; and CC Bordeianu, Univ Bucharest, 2007. Support by National Science Foundation */ // Newton_fd.java: Newton-Raphson root finder with forward diff deriv public class Newton_fd { public static double f(double x) { // Function to find zero return 2*Math.cos(x)-x; } public static void main(String[] argv) { double eps = 1e-6; // Tolerance double df, x = 2., dx = 1e-2; ; int it, imax = 100; // Max no of iterations // Iterations for ( it=1; it <= imax; it++ ) { // Forward diff derivative df = ( f(x + dx) - f(x))/dx; dx = -f(x)/df; x += dx; // New guess System.out.println("Iterate #= "+it+" x = "+x+" f(x)= "+f(x)); // Check for convergence if ( Math.abs(f(x)) <= eps ) { System.out.println("Root found with precison = " + eps); break; } } } }