interface NewtonFunction { float newtonfun(float d); float newtonfunDiff(float d); boolean newtonIsDiffImplemented (); } public class NewtonIter { float findRoot (NewtonFunction fun, float s) { float s_old = s+1; int iters = 0; while ( abs(s-s_old) > 1e-4 && iters < 30 ) { s_old = s; float d = 0; if ( fun.newtonIsDiffImplemented () ) d = fun.newtonfunDiff (s); else d = diff (fun,s); if ( abs(d) < 1e-6 ) return s; s = s - fun.newtonfun(s)/d; iters++; } return s; } float diff (NewtonFunction fun, float s) { // no scaling, cause s normalized float h =1e-4; float tmp = s+h; h = tmp - s; return ( (fun.newtonfun(s+h)-fun.newtonfun(s-h))/(2*h)); } }