Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nth root of a number in Ruby?

Tags:

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.

like image 203
ave Avatar asked Jan 16 '14 08:01

ave


People also ask

How do you find the nth root of a number in Java?

pow(n, 1.0 / 3) % ((int) Math. pow(n, 1.0 / 3)) . Use BigDecimal class, which is decimal representation of real numbers with arbitrary precision. Of course there's no method to calculate nth roots in the BigDecimal class.


2 Answers

Using ** with 1/3:

125 ** (1.0/3)
# => 4.999999999999999
like image 121
falsetru Avatar answered Sep 20 '22 19:09

falsetru


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]
like image 27
Arup Rakshit Avatar answered Sep 18 '22 19:09

Arup Rakshit