Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Calculate the nth root of a number

I'm trying to get the nth root of a number using JavaScript, but I don't see a way to do it using the built in Math object. Am I overlooking something?
If not...

Is there a math library I can use that has this functionality?
If not...

What's the best algorithm to do this myself?

like image 664
Nathan Avatar asked Sep 05 '11 13:09

Nathan


People also ask

How do you find the cubed root of a number in JavaScript?

The Math. cbrt() method returns the cubic root of a number.


2 Answers

Can you use something like this?

Math.pow(n, 1/root); 

eg.

Math.pow(25, 1/2) == 5 
like image 200
Digital Plane Avatar answered Sep 22 '22 00:09

Digital Plane


The nth root of x is the same as x to the power of 1/n. You can simply use Math.pow:

var original = 1000; var fourthRoot = Math.pow(original, 1/4); original == Math.pow(fourthRoot, 4); // (ignoring floating-point error) 
like image 36
Jeremy Avatar answered Sep 21 '22 00:09

Jeremy