开发者

How wrong do I use Math.Pow(a,b) function in this C# code?

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 compile开发者_Go百科r 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

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.


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.


The answer is an complex number: 1.0+1.732050807568877i. .NET's Math class does not support complex numbers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜