0

Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?

Language c++ I'm declaring an array and i save numbers (type double) in it. Then i start comparing the difference between each two elements in the array. for example

a[1] = 0.05
a[2] = 0.1
a[3] = 0.15

so when i do the following

if(a[3] - a[2] == a[2] - a[1] )

the condition becomes false!!

After debugging, i found out that 0.05 is saved in the array as 0.0499......993 and the case is similar with 0.10 and 0.15

How can i overcome this problem?

Community
  • 1
  • 1
Ahmed
  • 9
  • 1
  • 2

4 Answers4

8

You should never compare floating point numbers for exact equality.

You should read What Every Computer Scientist Should Know About Floating-Point Arithmetic to figure out why.

unwind
  • 364,555
  • 61
  • 449
  • 578
3

If you want to do exact calculations, you might want to look into using rational numbers. It is possible to implement a class for rational numbers in C++. Boost.Rational is an example of this.

If you want to use floating point, you probably want to do comparisons for "closeness", rather than equality, like this:

const float EPSILON = 0.0001; //< Some acceptable limit for equivalence
float d1 = a[3] - a[2];
float d2 = a[2] - a[1];

if (fabs(d1 - d2) < EPSILON) {
    // Consider d1 and d2 eqivalent
}
Magnus Hoff
  • 20,105
  • 8
  • 58
  • 81
2

Floating point mathematics is one area where computers will not give results as you would normally expect. See this for reference.

What you can do is consider something like delta = 0.00001
and check if fabs((a[3]-a[2]) - (a[2]-a[1])) < delta

Note: If this has anything to do with currency or monetary data then just use integers/long etc. Using float/double to represent money is a bad bad thing, for reasons mentioned above and explained further in the link above.

Sujoy
  • 7,102
  • 3
  • 27
  • 36
0

You've got several options:

(1) Use a type that stores these numbers precisely. For these numbers, it's easiest probably to use int and store them as 100x the original number.

(2) figure out that comparing doubles for equality is a bad strategy. See, when you store numbers as doubles, there are numbers that can't be represented exactly in binary in a fixed number of bits. 0.05 (as well as 0.5 5 50 and so on) is one of those numbers.

Charlie Martin
  • 103,438
  • 22
  • 180
  • 253