简体   繁体   English

C ++ POW(X,Y)X负双精度数和Y负双精度数,得出nan

[英]C++ POW(X,Y) X negative double and Y negative double, gives nan as result

I'm trying to do a simple operation, pow(-0.89,-0.67) in my C++ 14 code, and it gives a NaN as result. 我试图做一个简单的操作,在我的C ++ 14代码中pow(-0.89,-0.67) ,它给出了NaN作为结果。 When doing the same in SciLab the result is -1.08. 在SciLab中执行相同操作时,结果为-1.08。 Is there any way in C++ to get the right result? C ++中有什么方法可以得到正确的结果?

I am guessing that you made a typo in SciLab. 我猜您是在SciLab中打错字了。 You must have written 你一定写过

-0.89 ^ -0.67

Which means you did -(0.89 ^ -0.67) = -(1.08). 这意味着您做了-(0.89 ^ -0.67)=-(1.08)。

If you instead typed 如果您改为输入

(-0.89) ^ -0.67

You would have gotten the answer -0.5504 - 0.9306i. 您将获得答案-0.5504-0.9306i。 The negative root of a negative number is complex, and the pow function in C++ will give you a NaN result. 负数的负根很复杂,C ++中的pow函数将为您提供NaN结果。

If you use the std::complex type, you will get the correct answer of -0.5504 - 0.9306i: 如果使用std::complex类型,则将得到-0.5504-0.9306i的正确答案:

#include <iostream>
#include <complex>
#include <cmath>

int main()
{
    std::complex<double> a(-0.89), b(-0.67);
    std::cout << std::pow(a,b) << std::endl; 
}

output: 输出:

(-0.550379,-0.93064)

From the documentation of pow() , you have: pow()的文档中,您可以:

If base is negative and exponent is not an integral value, or if base is zero and exponent is negative, a domain error occurs, setting the global variable errno to the value EDOM. 如果base为负且指数不是整数值,或者base为零且指数为负,则会发生域错误,请将全局变量errno设置为EDOM值。

So, the nan result you are getting is expected. 因此,您得到的nan结果是可以预期的。


You could do it like this: 您可以这样做:

printf ("-0.89 ^ -0.67 = %f\n", -pow (0.89,-0.67) );

which gives: 这使:

-0.89 ^ -0.67 = -1.081207


Links I was based into: 我基于的链接:

  1. c++ pow function- invalid result? C ++ POW功能-无效的结果?
  2. pow() problem pow()问题

Nice question, +1! 好问题,+ 1!

It's always good to consult the standard: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf It says: 最好参考以下标准: http : //www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf它说:

— pow(x, y) returns a NaN and raises the ''invalid'' floating-point exception for finite x < 0 and finite non-integer y. — pow(x,y)返回一个NaN并引发有限x <0和有限非整数y的“无效”浮点异常。

Therefore, your C++ compiler is right. 因此,您的C ++编译器是正确的。 It should return NaN. 它应该返回NaN。

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

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