Greater than operator is wrong

Apr 14, 2016 at 6:47am
Here is a MCVE of a ">" operator behavior I do not really understand, although I suspect it has something to do with number precision:

#include <iostream>

int main(){
double var1, var2;
var1 = 1.91;
var2 = 1.31;

for(int ii=0; ii<100; ++ii){
if(var2 > var1){
std::cout << "var2 = " << var2 << " is greater than var1 = " << var1 << std::endl;
return 0;
}
var2 += 0.01;
}
return 0;
}

This code returns:

var2 = 1.91 is greater than var1 = 1.91

Why is that? Are the numbers being printed not the same as the ones the code is using? This has probably been answered somewhere else before but finding it proved difficult
Apr 14, 2016 at 6:58am
Yes it has to do with precision/rounding errors. Relying on exact values when working with floating point values is generally not a good idea.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>

int main(){
	double var1, var2;
	var1 = 1.91;
	var2 = 1.31;
	
	std::cout << std::setprecision(20);

	for(int ii=0; ii<100; ++ii){
		if(var2 > var1){
			std::cout << "var2 = " << var2 << " is greater than var1 = " << var1 << std::endl;
			return 0;
		}
		var2 += 0.01;
	}
	return 0;
}

output:
var2 = 1.9100000000000005862 is greater than var1 = 1.9099999999999999201
Apr 14, 2016 at 8:11am
Thanks for the fast answer.
Topic archived. No new replies allowed.