Doing calculations with 3D vectors with floating point coordinates. Occasionally, I want to check if a vector is nonzero. However, with floating point numbers, there's always a chance of a rounding error.
Please, is there a standard way, in Python, to check if a floating point number is sufficiently close to zero? I can write
abs(x) < 0.00001, but it's the hard-coded cutoff that bugs me on general grounds...
Best How To :
Like Ami wrote in the comments, it depends on what you're doing. The system epsilon is good for single operation errors, but when you use already rounded values in further calculations, the errors can get much larger than the system epsilon. Take this extreme example:
print('%.20f\n' % sys.float_info.epsilon)
x = 0.1
for _ in range(25):
print('%.20f' % x)
x = 11*x - 1
With exact values,
x would always be 0.1, since 11*0.1-1 is 0.1 again. But what really happens is this:
Note that the original
x differed from 0.1 by far less than my system epsilon, but the error quickly grew larger than that epsilon and even your 0.00001 and now it's in the millions.
This is an extreme example, though, and it's highly unlikely you'll encounter something this bad. But it shows that the precision really depends on what you're doing, so you'll have to find a good way for your particular calculation.