I am about to develop a scientific calculator. My question is: How can I distinguish zero result from very small numbers using float number?
For example, for 0.3 - 0.2 - 0.1, the result is something like 1E-19, which is not pure zero (precision problem, of course). I want to print out the result (0.0). So I use the EPSILON to do the comparison with zero.
The problem is, for the calculation: 3E-19 - 2E-19 the result should be 1E-19. I should print out the exactly result (though small) 1E-19. But if I still use the EPSILON comparison, the result is forced to be zero.
So, again, my question is: How can I do the check for zero and very small numbers?
This is inherently not possible if you use binary floating point datatype.
Instead, if you want precise control over numeric precision and rounding, you should use a decimal number library, for example GNU Multiprecision (GMP) or Boost.Multiprecision.
You said that 0.3-0.2-0.1 is not 0 but rather 1E-19. Actually it's already float(0.3)-float(0.2)-float(0.1) which is no longer 0. Unless you explicit check if 0.3 could be encoded in float or double losslessly then there is no way you can check if the small number you get after the calculation is due to operand error or really a small number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With