[英]C++ Looping with doubles
Why is PRINT THIS in the code below never printing?为什么在下面的代码中 PRINT THIS 从不打印? I've already cout << shiftx and shifty to make sure that at some point, they both are 0.3.我已经 cout << shiftx 和 shifty 以确保在某些时候它们都是 0.3。
for(double shifty=0; shifty < 2; shifty+=.1) {
for(double shiftx=0; shiftx < 2; shiftx +=.1) {
if((shiftx == 0.3) && (shifty == 0.3)) {
cout << "PRINT THIS" << endl;
}
}
}
The golden rule is: avoid equality tests in floating-point.黄金法则是:避免在浮点中进行相等测试。
Neither 0.1 nor 0.3 can be exactly represented. 0.1 和 0.3 都不能精确表示。
Standard reading: What Every Computer Scientist Should Know About Floating-Point Arithmetic .标准阅读: 每个计算机科学家都应该知道的关于浮点运算的知识。
To solve your particular problem, you should iterate and perform comparisons using integer types.要解决您的特定问题,您应该使用 integer 类型进行迭代并执行比较。 Only convert to floating-point types when you actually need to.仅在实际需要时转换为浮点类型。 eg:例如:
for(int shifty=0; shifty < 20; shifty++) {
for(int shiftx=0; shiftx < 20; shiftx++) {
double shifty_double = shifty * 0.1;
double shiftx_double = shiftx * 0.1;
if((shiftx == 3) && (shifty == 3)) {
cout << "PRINT THIS" << endl;
}
}
}
This is probably due to rounding errors when using doubles since 0.3 isn't actually stored as exactly 0.3 internally.这可能是由于使用双精度数时的舍入错误,因为 0.3 实际上并没有在内部完全存储为 0.3。
A way to compare doubles would be to allow for some error in the comparison.比较双打的一种方法是在比较中允许一些错误。 Example例子
if(abs(shiftx - shifty) < 0.000001)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.