This question has already been answered:

Help, the problem is the following, there is such a code (it is possible to organize a cycle), the first two actions "-" give the correct result, but the last one gives result = 3.

6429192995513e-017

double x1=0.6; double x2=0.03; double x3=0.009; double result=0.639; result=result-x1; result=result-x2; result=result-x3; 

Reported as a duplicate by PashaPash member Aug 16 '17 at 9:41 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    If there is Hell on earth, this Hell is called floating-point calculation. - Dith
  • Binary decimal fractions may become infinite, hence the error. - sercxjo
  • If you have a desire to learn more about how floating arithmetic works and why the error occurs, I recommend you to familiarize yourself with the ECA project. The site is still quite raw, but it will lift the curtain of the mystery of floating arithmetic. - A. Korpusenko

1 answer 1

No wonder - it is floating point arithmetic. Depending on the order in which the calculations were made, the final result may differ slightly from the expected. Plus, rounding takes effect - it is not necessary that the computer will, say, 32 bit floating point numbers not be converted to 64 or 80 bit, read the result, and then overtake it back.

In this case, if you need to understand whether we received a zero, then you just need to enter the condition that result < epsilon . epsilon is some very small number, which will tell us about the indistinguishability of floating numbers. It can be picked up either in a practical way (considering the accuracy of the calculations that we need), or it can already be prepared using the functions of the language library or from header files.

See the article machine epsilon