1

I'm trying to calculate the real answer of the cubic root of a negative number using C#. Math.Pow(-2, (1.0/3.0)) results in NaN. How do I calculate the real answer in C#?

Some posts on StackOverflow already addressed how to calculate the cubic or nth root of a number. But none of them how to calculate this on a negative number, which results in complex numbers.

I'm trying to port an Excel sheet to C#. In Excel =POWER(-2;1/3) returns a real number.

According to this post, the cubic root of a negative base has a real number answer, and two complex number answers.

I'm not interested in mathematically most correct solution, but having the ported C# code behave exactly the same as the Excel's =POWER() function, which returns the real number answer.

phuclv
  • 37,963
  • 15
  • 156
  • 475
Johan Ahlqvist
  • 336
  • 2
  • 14
  • You can use an interop call? – Ctznkane525 May 04 '19 at 22:07
  • Possible duplicate of [Another way to calculate cube root in C#](https://stackoverflow.com/questions/28817740/another-way-to-calculate-cube-root-in-c-sharp) – phuclv May 05 '19 at 04:02
  • there are a lot of duplicates: [Find Cube root of a number Using System.Math.Pow() method in C#](https://stackoverflow.com/q/25743901/995714), [C# math.pow cube root calculation](https://stackoverflow.com/q/38942580/995714) – phuclv May 05 '19 at 04:04
  • 2
    First `1.0/3.0` is rounded because it can not be represented exactly so you are losing precision even before you start computing. To remedy that see [Power by squaring for negative exponents](https://stackoverflow.com/a/30962495/2521214) on how to compute that on your own. Second the result of `(-2)^(1.0/3.0)` is not real number that is why `NaN` is returned. I do not know how your EXCEL is doing this so probably `pow(fabs(-2),(1.0/3.0))` or `|pow(-2,(1.0/3.0))|` which is on complex domain – Spektre May 05 '19 at 07:14

2 Answers2

1

The easiest way would be to write your own function that does something like this:

private static double CubeRoot(double x) {
    if (x < 0)
        return -Math.Pow(-x, 1d / 3d);
    else
        return Math.Pow(x, 1d / 3d);
}
Tim
  • 5,940
  • 1
  • 12
  • 18
  • 1
    why on earth do you use float in a double function? It's far less precise than `1.0/3.0` – phuclv May 05 '19 at 04:01
  • Indeed, 1d/3d would be better, oops. Updated my answer to use double-precision floating point. – Tim May 05 '19 at 14:06
1

Math.Cbrt() was introduced in .NET Core/Standard 2.1 to calculate cube root. Now you can get both mathematically correct and more precise result than before

Just call Math.Cbrt(-2)

phuclv
  • 37,963
  • 15
  • 156
  • 475