This is my source code:
#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;
}
What it does is calculating area between the curves. There is a loop in main() - its purpose is to calculate value as precise as it's possible within 3 decimal places.
It didn't work. For the sake of debugging, I added the line which is the only commented one. I wanted to know what's going on inside the loop.
//cout << current << endl;
When the line is there - when I uncomment it - everything works fine. When it's not - the loop seems to be infinite.
Holy Compiler, why?
It's not the matter of imprecise floating-point numbers, which I am aware of. Everything is finished withing 4 repeats of the loop content when I'm outputting current value inside it.