ave
ave

Reputation: 19443

How to get nth root of a number in Ruby?

For example

x ** 3 # => 125

Knowing that the result of applying ** with an argument 3 to x is 125, how can I get the value of x? Is there some kind of built-in method for this? I have been looking at the Math module but didn't find anything similar.

Upvotes: 20

Views: 7421

Answers (3)

danielricecodes
danielricecodes

Reputation: 3586

You can do an Nth root by raising to a fractional power. For example, the 4th root of 625 is 5.

(BigDecimal(625)**(1.0/4.0)).to_f
# => 5.0

Note, the .to_f is added for readability in this answer only. Don't cast it to a Float in your code unless you need to. IMHO, BigDecimals are "better" than Floats in Ruby - Floats lose precision too easily and you won't get accurate results. Case in point the accepted awnser above. The cube root of 125 is not 4.99999(repeat). It is 5.0 exactly.

Edit: the Ruby Class Rational seems to handle nth roots a little better.

2.3.3 :007 > 625.to_r ** 0.25
=> 5.0

But it still isn't as precise with a number that produces an irrational root.

2.3.3 :024 > (999.to_r ** 0.25) ** 4
=> 998.9999999999999

Close...but you should be able to get back to 999.0 exactly. My Mac's calculator and excel can do it. Main point - just be careful. If precision is important, Ruby may not handle this exactly the way one would expect.

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118271

You could also try as below :

irb(main):005:0> 125**(3**-1)
=> 5
irb(main):006:0> 125**(3**-1.0)
=> 4.999999999999999
irb(main):007:0>

update

C:\Users >ruby -v
ruby 1.9.3p448 (2013-06-27) [i386-mingw32]

Upvotes: 1

falsetru
falsetru

Reputation: 369054

Using ** with 1/3:

125 ** (1.0/3)
# => 4.999999999999999

Upvotes: 30

Related Questions