Addem
Addem

Reputation: 3919

Haskell: Find the nth root of a float

Wondering if there's a way to compute the nth root of a float in Haskell. I could try to write an algorithm but before I do, want to know if there's a module or canned function that I'm not finding. I found this page:

https://hackage.haskell.org/package/dimensional-1.0.1.0/docs/Numeric-Units-Dimensional.html

which mentions an nroot function but can't tell how to get access to it. It doesn't come in the standard library (when I try to run nroot(3,27) it tells me the function isn't in scope). I tried importing Numeric.Units.Dimensional by entering import Numeric.Units.Dimensional but was told it couldn't find the module. I may be misunderstanding how to load modules like this one.

Upvotes: 1

Views: 4529

Answers (1)

Alec
Alec

Reputation: 32319

Note that the definition of an nth root is really just exponentiation by the reciprocal of n. With that in mind, you are probably just best served writing 27 ** (1 / 3) or 27 ** (recip 3). If you really want:

nroot :: (Integral a, Floating b) => a -> b -> b 
n `nroot` x = x ** (1 / fromIntegral n)

That said, beware of the three exponentiation operators that exist! Only ** works for you.


I should probably add that nroot :: (KnownTypeInt n, Floating a) => Proxy n -> Quantity d a -> Quantity (Root d n) a is certainly not what you want. Note in particular that the root your are taking has to be a compile-time type level number.

Upvotes: 5

Related Questions