Formulation of the condition "close enough to zero"

Performing calculations with 3D vectors with floating point coordinates. Sometimes I want to check if a vector is different from zero. However, with floating point numbers, there is always the possibility of rounding errors.

Please, is there a standard way in Python to check if a floating point number is close enough to zero? I can write abs(x) < 0.00001, but this is a hard-coded circumcision that deceives me on a common basis ...

+4
source share
2 answers

As Ami writes in the comments, it depends on what you do. The epsilon system is good for single operation errors, but when using already rounded values ​​in further calculations, errors can be much larger than system epsilon. Take this extreme example:

import sys
print('%.20f\n' % sys.float_info.epsilon)
x = 0.1
for _ in range(25):
    print('%.20f' % x)
    x = 11*x - 1

With exact values, xthere will always be 0.1, since 11 * 0.1-1 is again 0.1. But actually the following happens:

0.00000000000000022204

0.10000000000000000555
0.10000000000000008882
0.10000000000000097700
0.10000000000001074696
0.10000000000011821655
0.10000000000130038202
0.10000000001430420227
0.10000000015734622494
0.10000000173080847432
0.10000001903889321753
0.10000020942782539279
0.10000230370607932073
0.10002534076687252806
0.10027874843559780871
0.10306623279157589579
0.13372856070733485367
0.47101416778068339042
4.18115584558751685051
44.99271430146268357930
493.91985731608951937233
5432.11843047698494046926
59752.30273524683434516191
657274.33008771517779678106
7230016.63096486683934926987
79530181.94061353802680969238

Please note that the original xdiffered from 0.1 much less than my system epsilon, but the error grew quickly more than epsilon and even your 0.00001, and now it is in millions.

This is an extreme example, though, and it is unlikely that you will encounter anything so bad. But this shows that the accuracy really depends on what you are doing, so you need to find a good way for your specific calculation.

+3

, , , isclose , .

0

All Articles