Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish zero from very small number in floating-form

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?

like image 663
guan boshen Avatar asked Apr 19 '16 04:04

guan boshen


2 Answers

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.

like image 164
Lie Ryan Avatar answered Sep 30 '22 02:09

Lie Ryan


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.

like image 37
Wei Shen Avatar answered Sep 30 '22 01:09

Wei Shen