
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. Udo. -- Walk softly and carry a BFG-9000.