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

吃可爱长大的小学妹 提交于 2019-12-23 03:50:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!