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

2006-10-15 Thread Jón Fairbairn
Vraj Mohan [EMAIL PROTECTED] 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.1
 
 
 
 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 [EMAIL PROTECTED]
http://www.chaos.org.uk/~jf/Stuff-I-dont-want.html  (updated 2006-09-13)

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe


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

2006-10-15 Thread Jón Fairbairn
I wrote:

 Vraj Mohan [EMAIL PROTECTED] wrote:
  (The equivalent code is well-behaved on MIT Scheme)
 
 Is it? Is there equivalent code to “my_sqrt :: Float -
 Float”? (that might be pertinent).

By which I mean HINT. (And one of the places to look for
bugs is where you have hand coded a constant without due
consideration of the implications).

-- 
Jón Fairbairn [EMAIL PROTECTED]
http://www.chaos.org.uk/~jf/Stuff-I-dont-want.html  (updated 2006-09-13)

___
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe