Newton's Method
Following code evaluates functions using Newton's Method. In this case it is f(x)=x^2-401.
To evaluate another function change the variable f0 and df0, which are the function and the derivative of the function, respectively.
f(x0) x1 = x0 - ------- f'(x0) f(x1) x2 = x1 - ------- f'(x1) ... and so forth
// Saved at Newton.hx // Compiled as haxe -main Newton -neko Newton.n // Run as neko Newton.n import neko.Sys; class Newton{ public static function main(){ neko.Lib.println("Enter Starting Point"); var x0 : Float = Std.parseFloat(neko.Sys.stdin().readLine()); neko.Lib.println("How Many Iterations?"); var count : Int = Std.parseInt(neko.Sys.stdin().readLine()); // Initialization of variables var f0 : Float; var df0 : Float; var p0 : Float; var p1 : Float; p0=x0; // Initial guess at x0 for(i in 0...count) { f0=x0*x0-401; // f(x) = x^2-401 or evaluate sqrt(401) df0=2*x0; // f'(x) = 2x (derivative of f(x)) p1=p0-(f0/df0); // p1=p0-(f(x)/f'(x)) Newton's Method Here neko.Lib.println("p1 = " + p1); p0=p1; //switch variables for next iteration x0=p1; //switch variables for next iteration } } }
version #14226, modified 2012-06-12 03:39:50 by robwheel