本文介绍了古怪:( - 0.666667 + 0.333333)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在一个程序中遇到一些奇怪的东西,当减去2 (double)的时候会导致0 ,但它返回 -1.11022e-16。在我看来,将双x_step decleration 更改为无符号类型可能有所帮助,但编译器在我尝试时会抱怨。 任何想法? #include< iostream> 使用命名空间std; int main(int argc,char * argv []){ double x1 = -1; double x2 = 1; double nx = 6; int pos = 0; double x = 0.0; double x_step = 0.0; x_step =(x2 - x1)/ nx; x = x1; for(pos = 0; pos< nx; pos ++){ cout<< x<< " + \t" << x_step<< " = \t" << (x + x_step)<< endl; x = x + x_step; } 返回0; } 输出: -1 + 0.333333 = -0.666667 -0.666667 + 0.333333 = -0.333333 -0.333333 + 0.333333 = -1.11022e-16 -1.11022e-16 + 0.333333 = 0.333333 0.333333 + 0.333333 = 0.666667 0.666667 + 0.333333 = 1 解决方案 这就是浮点运算的本质。你不应该将 与精确值进行比较,因为舍入错误(这是不可避免的, 虽然通常非常小)。 你应该检查一些小的epsilon范围,而不是比较 的确切数字。 - :: bartekd [at] o2 [dot] pl 这是浮点运算的本质。因为舍入错误(这是不可避免的,但通常非常小),你不应该与确切的值进行比较。 你应该检查一些小的epsilon范围而不是比较确切的数字。 问题在于计算机上的实数具有有限的准确性。 减去两个(几乎)相等的实数的结果应该不值得信任。这个问题的解决方案通常取决于你想要做什么。 再见, Chris Dams Hi, I''m experiencing some weirdness in a program, when subtracting 2(double)''s which should result in 0, but instead it returns-1.11022e-16. It looks to me that changing the double x_step declerationto unsigned type, might help, but the compiler complains when i try that. Any ideas ? #include <iostream>using namespace std; int main(int argc, char *argv[]) { double x1 = -1;double x2 = 1;double nx = 6;int pos = 0;double x = 0.0;double x_step = 0.0; x_step = (x2 - x1) / nx; x = x1;for (pos = 0; pos < nx; pos++) {cout << x << " +\t" << x_step << " =\t " << (x +x_step) << endl;x = x + x_step;} return 0;}Output: -1 + 0.333333 = -0.666667-0.666667 + 0.333333 = -0.333333-0.333333 + 0.333333 = -1.11022e-16-1.11022e-16 + 0.333333 = 0.3333330.333333 + 0.333333 = 0.6666670.666667 + 0.333333 = 1 解决方案 That''s the nature of floating point arithmetic. You shouldn''t compareagainst exact values, beacause of rounding errors (which are unavoidable,though usually very small). You should check against some small epsilon range instead of comparingexact numbers. --:: bartekd [at] o2 [dot] pl That''s the nature of floating point arithmetic. You shouldn''t compare against exact values, beacause of rounding errors (which are unavoidable, though usually very small). You should check against some small epsilon range instead of comparing exact numbers. The problem is that real numbers on a computer have limited accuracy.Results of substracting two real numbers that are (almost) equal, shouldnot be trusted. Solutions to this problem generally depend on whatexactly you want to do. Bye,Chris Dams 这篇关于古怪:( - 0.666667 + 0.333333)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-18 21:28