21

I use below method to calculate Nth Root of double value, but it takes a lot of time for calculating the 240th root. I found out about Newton method, but was not able to implement it into a method. Any help would be appreciated.

static double NthRoot(double A, int N)
{
   double epsilon = 0.00001d;//
   double n = N;
   double x = A / n;
   while (Math.Abs(A-Power(x,N)) > epsilon)
   {
    x = (1.0d/n) * ((n-1)*x + (A/(Power(x, N-1))));
   }
   return x;
}
Scath
  • 3,777
  • 10
  • 29
  • 40
illusion
  • 383
  • 2
  • 4
  • 9
  • did you have a look at this? http://en.wikipedia.org/wiki/Newton%27s_method#Pseudocode should no be too difficult to translate into real code – DrCopyPaste Sep 06 '13 at 12:13
  • 1
    What actually is the question here? Do you just want it to be faster? Or do you explicitly want to see how the newton method would look in real code? – DrCopyPaste Sep 06 '13 at 12:16
  • I came across POW, but for some reason I though it's same as per the method I posted above. I'm not programmer, and would not have posted question here unless I was not able to figure it out myself. Thank you – illusion Sep 06 '13 at 12:29
  • Where did you get that power-method from? Is it selfwritten or what namespace is it in? – DrCopyPaste Sep 06 '13 at 12:34
  • From here http://stackoverflow.com/questions/3848640/n-th-root-algorithm , It's funny, I came across Pow but I thought it could not be so simple after learning the method mentioned above. I'm learning (C# by (learn what I need), I try to write indicators for a trading program NinjaTrader. – illusion Sep 06 '13 at 12:38

2 Answers2

63
static double NthRoot(double A, int N)
{
    return Math.Pow(A, 1.0 / N);
}

From Wikipedia:

In calculus, roots are treated as special cases of exponentiation, where the exponent is a fraction:

\sqrt[n]{x} \,=\, x^{1/n} 
Stefan Dragnev
  • 14,143
  • 6
  • 48
  • 52
2

You can use the same function used to find the power of a number, just use reciprocal of the number instead of the number itself.

To find N root of X you can write,

int root = Convert.ToInt32(Math.Pow(X, (1 / N)); 
LarsTech
  • 80,625
  • 14
  • 153
  • 225
Abhas Bhoi
  • 349
  • 3
  • 3