[Haskell-cafe] Application of iterate

Bernie Pope bjpop at csse.unimelb.edu.au
Fri Mar 23 07:41:55 EDT 2007


> It is :-
> 
> my_sqrt t = last (take 20 (iterate (\n -> n/2 + t/(2 * n)) t))
> 
> It is a bit crude though.  20 iterations is a bit arbitrary. I don't
> suppose
> there is a easy way to iterate until the results stop changing.

Here's something for you to play with:

   my_sqrt t = fix (\n -> n/2 + t/(2 * n)) t

   fix :: (Double -> Double) -> Double -> Double
   fix f x
      | x == fx = x
      | otherwise = f (fix f fx)
      where
      fx = f x

My numerical analysis is a bit on the dodgy side, but you probably don't
want to use == to test for convergence.

Maybe you can find a nice way to write fix using some prelude functions?

Cheers,
Bernie.



More information about the Haskell-Cafe mailing list