-1

Take this c++ code:

double d = 0.3028 + 0.0028;
cout << d << endl;
if (d == 0.3056)
    cout << "match" << endl;
else
    cout << "not a match" << endl;

Why is the output "not a match"?

Tim Johnsen
  • 144
  • 10

2 Answers2

1

Well that is because how floats are stored in memory. Here is a good article on this: https://dev.to/visheshpatel/how-floating-point-no-is-stored-memory-47od

Instead floats (and doubles) should be checked if are "almost equal". In your case, if you are interested only in 4 decimal places then you can check if the difference is lower than 0.00001. So:

float epsilon = 0.00001;

double a = d; //your value
double b = 0.3056; //the value to which you are comparing

bool equal_ab = abs(a - b) < epsilon;
Bartosz Pachołek
  • 1,278
  • 1
  • 8
  • 17
0

This is the nature of finite precision math.

If you use, say, six digits of decimal precision, 1/3 will be represented as 0.333333 and if you do "3 * 1/3" you will get 0.999999, not 1.

Similarly, 2/3 will be 0.666667, so 2 * 1/3 will not give 2/3. 1/3+1/3 will give 0.666666, not 2/3.

Finite precision representations are funny this way and testing them for precise equality is generally a bad idea.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278