/* 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_cd.java: Newton-Raphson root finder, central diff deriv public class Newton_cd { public static double f(double x) // Find zero of this function { return 2*Math.cos(x) - x; } public static void main(String[] argv) { double x = 2., dx = 1e-2, F= f(x), eps = 1e-6, df; int it, imax = 100; // Max no of iterations permitted // Iterate for ( it = 0; it <= imax; it++ ) { System.out.println("Iteration # = "+it+" x = "+x+" f(x) = "+F); // Central diff deriv df = ( f(x + dx/2) - f(x-dx/2) )/dx; dx = -F/df; x += dx; // New guess F = f(x); // Save for use // Check for convergence if ( Math.abs(F) <= eps ) { System.out.println("Root found, tolerance eps = " + eps); break; } } } }