public class RootFinder { // Java version, based on Numerical Recipes, p. 354 public static final int JMAX= 40; // Maximum number of bisections public static final double ERR_VAL= -10E10; public static int j; public static double rtbis(MathFunction func, double x1, double x2, double xacc) { double dx, xmid, rtb; double f= func.f(x1); double fmid= func.f(x2); if (f*fmid >= 0.0) { System.out.println("Root must be bracketed for bisection"); return ERR_VAL; } // Orient search so f>0 lies at x + dx if (f < 0.0) { dx= x2 - x1; rtb= x1; } else { dx= x1 - x2; rtb= x2; } for (j=0; j < JMAX; j++) { dx *= 0.5; xmid= rtb + dx; fmid= func.f(xmid); if (fmid <= 0.0) rtb= xmid; if (Math.abs(dx) < xacc || fmid == 0.0) { System.out.println("\nBisection iterations: "+ j); return rtb; } } System.out.println("Too many bisections"); return ERR_VAL; } }