C++ POW(X,Y) X negative double 和 Y negative double,给出 nan 作为结果
C++ POW(X,Y) X negative double and Y negative double, gives nan as result
我正在尝试在我的 C++ 14 代码中执行一个简单的操作 pow(-0.89,-0.67)
,它给出了 NaN
作为结果。在 SciLab 中执行相同操作时,结果为 -1.08。在 C++ 中有什么方法可以得到正确的结果吗?
根据 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.
所以,您得到的 nan 结果是符合预期的。
你可以这样做:
printf ("-0.89 ^ -0.67 = %f\n", -pow (0.89,-0.67) );
给出:
-0.89 ^ -0.67 = -1.081207
我基于的链接:
- c++ pow function- invalid result?
- pow() problem
好问题,+1!
我猜你在 SciLab 中打错了字。你一定写过
-0.89 ^ -0.67
这意味着你做了 -(0.89 ^ -0.67) = -(1.08).
如果您改为输入
(-0.89) ^ -0.67
你会得到答案 -0.5504 - 0.9306i。负数的负根很复杂,C++ 中的 pow
函数会给你一个 NaN 结果。
如果你使用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;
}
输出:
(-0.550379,-0.93064)
参考标准总是好的:
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.
因此,您的 C++ 编译器是正确的。它应该 return NaN。
我正在尝试在我的 C++ 14 代码中执行一个简单的操作 pow(-0.89,-0.67)
,它给出了 NaN
作为结果。在 SciLab 中执行相同操作时,结果为 -1.08。在 C++ 中有什么方法可以得到正确的结果吗?
根据 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.
所以,您得到的 nan 结果是符合预期的。
你可以这样做:
printf ("-0.89 ^ -0.67 = %f\n", -pow (0.89,-0.67) );
给出:
-0.89 ^ -0.67 = -1.081207
我基于的链接:
- c++ pow function- invalid result?
- pow() problem
好问题,+1!
我猜你在 SciLab 中打错了字。你一定写过
-0.89 ^ -0.67
这意味着你做了 -(0.89 ^ -0.67) = -(1.08).
如果您改为输入
(-0.89) ^ -0.67
你会得到答案 -0.5504 - 0.9306i。负数的负根很复杂,C++ 中的 pow
函数会给你一个 NaN 结果。
如果你使用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;
}
输出:
(-0.550379,-0.93064)
参考标准总是好的: 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.
因此,您的 C++ 编译器是正确的。它应该 return NaN。