[Haskell-cafe] Re: Debugging Newton's method for square roots

Jón Fairbairn jon.fairbairn at cl.cam.ac.uk
Sun Oct 15 08:55:01 EDT 2006


Vraj Mohan <r.vrajmohan at gmail.com> writes:

> I am new to Haskell and need help in debugging my code.
> 
> I wrote the following function for calculating square roots using Newton's 
> method:
> 
> my_sqrt :: Float -> Float
> my_sqrt x = improve 1 x
>          where improve y x = if abs (y * y - x) < epsilon 
>                                 then y 
>                                 else improve ((y + (x/y))/ 2) x
>                epsilon = 0.00001
> 
> 
> 
> This works for several examples that I tried out but goes into an infinite loop
> for my_sqrt 96.

Generally it's better to separate out the different parts of
the algorithm. So 

sqrt_step x candidate = (candidate + x/candidate)/2

Now you can try 

take 20 $ iterate (sqrt_step 2) 1

and watch the convergence.  When you're happy with that, you
can use something like “head . dropWhile unconverged”.

> (The equivalent code is well-behaved on MIT Scheme)

Is it? Is there equivalent code to “my_sqrt :: Float ->
Float”? (that might be pertinent).

-- 
Jón Fairbairn                                 Jon.Fairbairn at cl.cam.ac.uk
http://www.chaos.org.uk/~jf/Stuff-I-dont-want.html  (updated 2006-09-13)



More information about the Haskell-Cafe mailing list