简体   繁体   English

在此C#代码中使用Math.Pow(a,b)函数有何错误?

[英]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": 我找不到以下代码有什么问题,MSVC#编译器将NAN存储在“ c”中:

double c = Math.Pow(-8d, 1d / 3d);

While I think this line should calculate -2 for "c", the compiler stores NAN in "c"? 虽然我认为这一行应该为“ c”计算-2,但是编译器将NAN存储在“ 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. 实际上,1/3不能完全表示为浮点数,但需要四舍五入。 An exact real result for the rounded exponent does not even exist in theory. 在理论上,甚至没有关于舍入指数的确切实际结果。

Normally, one wouldn't say that (-8)^(1/3) = -2. 通常,人们不会说(-8)^(1/3)= -2。

Indeed it is true that (-2)^3 = -8, but powers of negative numbers are a complicated matter. 的确是(-2)^ 3 = -8,但是负数的幂是一件复杂的事情。

You can read more about the problem on Wikipedia : 您可以在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. 对数方法和有理指数方法都不能用于将a ^ r定义为负实数a和任意实数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.) 实际上,对于每个实数r,er都是正数,因此ln(a)并未定义为a≤0的实数。(另一方面,可以通过选择n的复数来定义负数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. 简而言之,在数学上很难正确定义a ^ r的值,当a为负数时,以免一个人开始使用复数,因此,一般而言,应该避免尝试这样做。

The answer is an complex number: 1.0+1.732050807568877i . 答案是一个复数: 1.0+1.732050807568877i .NET's Math class does not support complex numbers. .NET的Math类不支持复数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM