Nth Root in Ruby

P

Peter Laurens

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
 
A

Alex LeDonne

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

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
 
R

Ron Fox

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
 
P

Peter Laurens

Alex said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,817
Latest member
DicWeils

Latest Threads

Top