Wednesday, January 28, 2009

Ch3, Ex2


declare CubeRoot
fun {CubeRoot N}
%can come from outside to make it more modular
Precision = 0.00001
InitialGuess = 1.0
%convert N to float
X = if {Int.is N} then {Int.toFloat N} else N end
fun {GoodEnough Guess}
{Number.abs (Guess*Guess*Guess-X)} < Precision
end
fun {Improve Guess}
(X/(Guess*Guess)+2.0*Guess)/3.0
end
fun {NewtonCubeRoot Guess}
%{Browse Guess} %Print the Guesses made, just to debug
if {GoodEnough Guess} then Guess
else {NewtonCubeRoot {Improve Guess}}
end
end
in
{NewtonCubeRoot InitialGuess}
end
%Tests
{Browse {CubeRoot 0.008}}
{Browse {CubeRoot 27}}

No comments:

Post a Comment