Subtracting two doubles gives an odd result

Hi

I've run the following code:

1
2
3
4
5
6
7
  double d = 342.389;
  double d_d = d - floor( d); //whats the decimal value i.e. 0.389 

  double n1 = d_d * 1000;
  double n2 = floor (d_d * 1000);
  double n3 = n1 - n2;
  cout << setprecision(6) <<n1 << " - " << n2 << " = " << n3;


and I get the following output:

 
389 - 389 = 1.00044e-11 //why is this not 0? 


I've thought quite a bit about this and just can't understand this result.

Thanks
Last edited on
Small rounding errors is to be expected when working with floating point numbers.

1.00044e-11 is just another way of writing 0.0000000000100044. This is a very small number. It's almost zero.
Ok thanks.

Is there a standard way of determining whether such a number is basically 0? i.e. how can I know whether n2 and n1 are the same?
You can use an epsilon value.

1
2
3
4
bool almost_equal(double a, double b, double epsilon = 0.000000001)
{
    return std::abs(a - b) < epsilon;
}


HOWEVER, the best solution here is to not make a comparison in the first place.
Please tell us why you are trying to exactly compare floating-point numbers.
There are most likely alternatives here that avoid comparing floating-point numbers for equality.
Topic archived. No new replies allowed.