I can not find anything wrong with the following code, whence the MSVC# compiler stores NAN in "c":
double c = Math.Pow(-8d, 1d / 3d);
While I think this line should calculate -2 for "c", the compiler stores NAN in "c"? Am i wrong about anything?
The power function for floating point numbers is only defined for positive base or integral exponent. Try
Actually, 1/3 can't be represented exactly as a floating point number, but needs to be rounded. An exact real result for the rounded exponent does not even exist in theory.
The answer is an complex number:
1.0+1.732050807568877i
. .NET's Math class does not support complex numbers.Normally, one wouldn't say that (-8)^(1/3) = -2.
Indeed it is true that (-2)^3 = -8, but powers of negative numbers are a complicated matter.
You can read more about the problem on Wikipedia:
In short, it's mathematically hard to properly define what a^r should be, when a is negative, lest one starts working with complex numbers, and therefore one in general should steer clear of trying to do that.