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

Udo Stenzel u.stenzel at web.de
Sun Oct 15 11:02:05 EDT 2006

Vraj Mohan wrote:
> 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. How do I go about debugging this code in GHC or Hugs?

1) As Jon said, by seperating the iteration from the selection of the
   result.  iterate, filter, head, etc. are your friends.  Makes the
   code more readable and maintainable, too.
2) By learning more about floating point numbers.  There is no Float y
   such that | y*y - 96 | < 0.00001.  That's why such an iteration is
   better terminated not when the result is good enough, but when it
   stops getting better.  It's also the reason why you code might work
   with -fexcess-precision or in an untyped language or with the next or
   previous compiler release or on rainy days or whatever else.

Walk softly and carry a BFG-9000.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20061015/8b9d87f8/attachment-0001.bin

More information about the Haskell-Cafe mailing list