问题
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?
回答1:
The power function for floating point numbers is only defined for positive base or integral exponent. Try
double c = - Math.Pow(8d, 1d / 3d);
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.
回答2:
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:
Neither the logarithm method nor the rational exponent method can be used to define a^r as a real number for a negative real number a and an arbitrary real number r. Indeed, er is positive for every real number r, so ln(a) is not defined as a real number for a ≤ 0. (On the other hand, arbitrary complex powers of negative numbers a can be defined by choosing a complex logarithm of a.)
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.
回答3:
The answer is an complex number: 1.0+1.732050807568877i
. .NET's Math class does not support complex numbers.
来源:https://stackoverflow.com/questions/4723320/how-wrong-do-i-use-math-powa-b-function-in-this-c-sharp-code