[Haskell-cafe] Fractional sqrt
Lennart Augustsson
lennart at augustsson.net
Thu Jan 18 19:28:05 EST 2007
I don't see a much better way than using something like Newton-
Raphson and testing for some kind of convergence. The Fractional
class can contain many things; for instance it contains rational
numbers. So your mysqrt function would have to be able to cope with
returning arbitrary precision results. As a first step you should
specify what mysqrt should return when it can't return the exact
result. For instance, what would you like mysqrt (2%1) to return?
-- Lennart
On Jan 18, 2007, at 18:15 , Novák Zoltán wrote:
> Hello,
>
> I would like to use the sqrt function on Fractional numbers.
> (mysqrt :: (Fractional a) => a->a)
>
> Half of the problem is solved by:
>
> Prelude> :t (realToFrac.sqrt)
> (realToFrac.sqrt) :: (Fractional b, Real a, Floating a) => a -> b
>
> For the other half I tried:
>
> Prelude> :t (realToFrac.sqrt.realToFrac)
> (realToFrac.sqrt.realToFrac) :: (Fractional b, Real a) => a -> b
>
> Prelude> :t (realToFrac.sqrt.fromRational.toRational)
> (realToFrac.sqrt.fromRational.toRational) :: (Fractional b, Real a)
> => a -> b
>
> Prelude> :t (realToFrac.sqrt.realToFrac.fromRational.toRational)
> (realToFrac.sqrt.realToFrac.fromRational.toRational) :: (Fractional b,
> Real a) => a -> b
>
> I have to admit that I do not fully understand the Haskell
> numerical tower...
> Now I'm using the Newton method:
>
> mysqrt :: (Fractional a) => a -> a
> mysqrt x = (iterate (\y -> (x / y + y) / 2.0 ) 1.0) !!2000
>
> But I want a faster solution. (Not by replacing 2000 with 100... :)
>
> Zoltan
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
More information about the Haskell-Cafe
mailing list