【发布时间】:2015-04-27 15:51:48
【问题描述】:
这是我的源代码:
#include <iostream>
#include <cmath>
using namespace std;
double up = 19.0 + (61.0/125.0);
double down = -32.0 - (2.0/3.0);
double rectangle = (up - down) * 8.0;
double f(double x) {
return (pow(x, 4.0)/500.0) - (pow(x, 2.0)/200.0) - 0.012;
}
double g(double x) {
return -(pow(x, 3.0)/30.0) + (x/20.0) + (1.0/6.0);
}
double area_upper(double x, double step) {
return (((up - f(x)) + (up - f(x + step))) * step) / 2.0;
}
double area_lower(double x, double step) {
return (((g(x) - down) + (g(x + step) - down)) * step) / 2.0;
}
double area(double x, double step) {
return area_upper(x, step) + area_lower(x, step);
}
int main() {
double current = 0, last = 0, step = 1.0;
do {
last = current;
step /= 10.0;
current = 0;
for(double x = 2.0; x < 10.0; x += step) current += area(x, step);
current = rectangle - current;
current = round(current * 1000.0) / 1000.0;
//cout << current << endl;
} while(current != last);
cout << current << endl;
return 0;
}
它的作用是计算曲线之间的面积。 main() 中有一个循环 - 其目的是尽可能精确地计算值,精确到小数点后 3 位。
没有用。为了调试,我添加了唯一注释的行。我想知道循环内部发生了什么。
//cout << current << endl;
当该行存在时 - 当我取消注释时 - 一切正常。如果不是 - 循环似乎是无限的。
神圣的编译器,为什么?
这不是不精确的浮点数的问题,我知道这一点。一切都在循环内容的 4 次重复内完成当我在其中输出当前值。
【问题讨论】:
-
您是否使用了调试器并检查了未定义的行为?阅读浮点数指南并抛弃
current != last。这极不可能是真的。 floating-point-gui.de -
浮点数容易出现舍入误差,并且在对它们进行运算时会加剧误差。所以例如
2.65不是 完全2.65但可能是例如2.649997或类似的东西。因此,您无法可靠地比较浮点数是否相等。 -
英特尔?双打在内存中是 64 位,但在内部是 80 位,并且对 cout 的调用可能会导致将值写入内存,从而失去精度,从而使以下测试评估为真。我会说“学习使用调试器”和“了解浮点数”
-
Is floating point math broken? 的可能重复项(实际上并非重复项,但很可能是此错误源)
-
如果不是四舍五入,如果我用
std::fabs(current - last) >= 1e-8替换current != last一切正常吗? ideone.com/kUqhhf 这都是关于四舍五入的。编译器可能会执行一些优化,这就是您获得无限循环的原因。这不是编译器的错,是你的错。
标签: c++ floating-point infinite-loop