浮点错误

Floating Point Error

本文关键字:错误      更新时间:2023-10-16

我的C++代码中有一个奇怪的错误:

float cosTheta = someFunction();
cout << cosTheta << endl;  // prints 1 on the console
if (cosTheta == 1) {       // doesn't enter this condition
    cout << "it is 1" << endl;
}
float sinTheta = sqrt(1 - pow(cosTheta, 2));
return (someVariable * sinTheta);

问题是:cosTheta 是 1,但它没有进入条件,尽管它在屏幕上打印 1。当我打印返回的值时,它应该是 0,因为 cosTheta 是 1,所以 sinTheta 得到 0,返回值得到 0,但我得到 0.0953562...

我在 Java 中测试了相同的代码,结果得到 0。

您不应该将浮点数与 == 进行比较。浮点运算中的舍入误差意味着您应该选择一个精度EPSILON(适合您的情况)并像这样使用它:

const float EPSILON = 0.00001;
if( fabs(cosTheta - 1) < EPSILON ) {
    cout << "It is approximately 1n";
}