JohnL4
JohnL4

Reputation: 1156

In Haskell, what is the most straightforward way to take roots of real numbers?

I'd like to take the cube root of a number in Haskell (GHCi, actually). In something like Java, I'd just do Math.Pow( x, 1.0/3.0) and move on, but I don't see a way to do that so easily in Haskell.

So, is there some simple idiom for taking arbitrary roots of arbitrary real numbers?

Upvotes: 2

Views: 464

Answers (1)

hugomg
hugomg

Reputation: 69944

AFAIK, there is no function to compute nth-roots in the standard library. However you could just use the same pow method from Java

nroot :: Floating a => Int -> a -> a
nroot n x = x ** (1.0 / fromIntegral n)

Or even more idiomatically:

nroot n x = x ** recip n

example:

nroot 4 81.0  -- returns 3.0

The ** operator is the equivalent of Java's Math.powand the fromIntegral is required to cast n from an int to a floating point value

Upvotes: 6

Related Questions