/* 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 */ // Bisection.java: Bisection root finder, crude, but reliable import java.io.* ; import java.text.* ; public class Bisection { public static double f(double x) { return 2*Math.cos(x)-x; } public static void main(String[] argv) { double eps = 1e-6; // Precision double x, xminus = 0., xplus = 7.; // Range must contain a 0 int it, imax = 100; // Max no iterations System.out.println("Iteration x f(x)"); DecimalFormat df = new DecimalFormat("#0.0000000000000000"); DecimalFormat in = new DecimalFormat("#00"); // Column formatted for( it=0; it <= imax; it++ ) { x = ( xplus + xminus )/2.; System.out.println(" "+in.format(it)+" "+df.format(x)+ " "+ df.format(f(x))); if ( f(xplus) * f(x) > 0. ) xplus = x; // Algorithm else xminus=x; if ( Math.abs(f(x)) < eps) { // Convergence check System.out.println("Root found with precision eps = " + eps); break; } } } }