# Nth Root in Ruby

**URL:** <https://www.ruby-forum.com/t/nth-root-in-ruby/117954>\
**Category:** Ruby\
**Created:** [October 22, 2007, 7:26pm UTC](https://www.ruby-forum.com/t/nth-root-in-ruby/117954 "2007-10-22T19:26:53Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jazcyk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e56c9b/32.png) [@jazcyk](https://www.ruby-forum.com/u/jazcyk)\
**Post date:** [October 22, 2007, 7:26pm UTC](https://www.ruby-forum.com/t/nth-root-in-ruby/117954/1 "2007-10-22T19:26:53Z")

</div>

Hi,

I have tried Googling, but am finding it difficult to track down an  
answer to my question:

What’s the easiest way to calculate the Nth root of a number in Ruby,  
I’ve looked at the Math module but this doesn’t seem to include this  
functionality unless I’m missing something. Do I need to roll my own?

Thanks,

- N

---

<div class="post-metadata">

**Author:** ![jazcyk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e56c9b/32.png) [@jazcyk](https://www.ruby-forum.com/u/jazcyk)\
**Post date:** [October 22, 2007, 7:34pm UTC](https://www.ruby-forum.com/t/nth-root-in-ruby/117954/2 "2007-10-22T19:34:25Z")

</div>

On 10/22/07, Peter L. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> - N

Try raising to the power of the reciprocal:

irb(main):001:0\> # calculate a third root  
irb(main):002:0\> 10.0 \*\* (1.0/3.0)  
=\> 2.15443469003188

-A

---

<div class="post-metadata">

**Author:** ![jazcyk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e56c9b/32.png) [@jazcyk](https://www.ruby-forum.com/u/jazcyk)\
**Post date:** [October 22, 2007, 7:35pm UTC](https://www.ruby-forum.com/t/nth-root-in-ruby/117954/3 "2007-10-22T19:35:14Z")

</div>

Alex LeDonne wrote:

> On 10/22/07, Peter L. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:
> 
> > - N
> 
> Try raising to the power of the reciprocal:
> 
> irb(main):001:0\> # calculate a third root  
> irb(main):002:0\> 10.0 \*\* (1.0/3.0)  
> =\> 2.15443469003188
> 
> -A

Of course - thanks.

---

<div class="post-metadata">

**Author:** ![jazcyk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e56c9b/32.png) [@jazcyk](https://www.ruby-forum.com/u/jazcyk)\
**Post date:** [October 23, 2007, 6:36pm UTC](https://www.ruby-forum.com/t/nth-root-in-ruby/117954/4 "2007-10-23T18:36:57Z")

</div>

def rootn(x,n)  
Math.exp(Math.log(x)/n)  
end

Probably should check for X \> 0 and do appropriate  
special case code if not.

RF
