Johan Ahlqvist
Johan Ahlqvist

Reputation: 346

Calculating the cubic root for negative number

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.

Upvotes: 1

Views: 1100

Answers (2)

phuclv
phuclv

Reputation: 41764

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)

Upvotes: 1

Tim
Tim

Reputation: 6060

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);
}

Upvotes: 1

Related Questions