循环中的C++浮点错误与单个表达式中的浮点错误相比



(免责声明:我知道浮点不能精确表示十分之一。(

我在C++中使用单精度浮点(以测试舍入误差(,遇到了这种奇怪的行为。

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
// set number of sigdigs in output
cout << setprecision(9);
float singleA = 0.1 * 7.;
float singleB = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
float singleC = 0.0;
for (int i = 0; i < 7; i++){
singleC += 0.1;
}
// ^ i expected that to be the same as
// 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1
cout << "multiplied:      " << singleA << endl;
cout << "added in one go: " << singleB << endl;
cout << "added in a loop: " << singleC << endl;
return 0;
}

输出:

multiplied:      0.699999988
added in one go: 0.699999988
added in a loop: 0.700000048

我想知道为什么在表达式中添加0.17次会得到与在循环中添加0.1.7次不同的结果。我都加了0.17倍,为什么会发生这种情况?singleB是否使用浮点十进制算法进行了优化

0.1double,而不是float。因此,当你在一个表达式中添加其中七个时,运算是使用双精度算术进行的,然后最终结果转换为单精度。在循环中,每次添加后都会丢弃额外的精度。用0.1f试试,你会得到相同的结果。

最新更新