Strange Float Value

My question is simple. Why does the program return the value of 7.45058e-09? I know this negligible at best and it might as well be zero, but why the inaccuracy? How can I avoid arithmetic mistakes such as these?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  // Example program
#include <iostream>
#include <string>
using namespace std;
#include <iomanip>

int main()
{
float value1 = 0.1f;
float value2 = 2.1f;
value1 -= 0.09f;  
value2 -= 2.09f;

cout << value1 - value2 <<endl;
return 0;
}
Last edited on
Hi,

Floating point values are not represented exactly - they use binary fractions.

Btw, double is the default because the precision of float is easily exceeded, it can only do 6 or 7 significant figures. double can do 15 or 16 :+) Only use float if some library requires it, typically a graphics library.

A simple way to solve this is to use std::setprecision. The default for std::cout is 6sf, so in this case if you set something less than that it will print zero with the number dp you specify. But that will not fly if you want more than 6, or need a definitive result for things like check for divide by zero, or equality.

One can use a precision value and relational tests to get the desired result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

//using namespace std; // <-- avoid this, Google why
#include <iomanip>
#include <cmath>

int main()
{
   const double precision = 0.001;

   const double value1 = 0.1;
   double value2 = 1.0 - (10.0 * value1);

   if(std::abs(value2) < precision ) {
      std::cout << "Value is zero - (less than " << precision << ")\n";
   }
   else {
      std::cout << "Value is not zero - (greater than " << precision << ")\n";
   }

return 0;
}


Can do something similar for equality - absolute value of the difference between the 2 numbers. Should write functions that return a bool type to do this.

Of course one wouldn't normally print out values like that, use the bool functions in tests to check for equality or zero.

Good Luck !!
Topic archived. No new replies allowed.