That "slight numerical error" is not a numerical error but a known issue with floating point numbers: they are sums of fractions of two stored binary and can't represent all real numbers.
If you wish to print precise n-digit numbers, you may want to print with the format string e.g. %.1f
instead of %f
.
To fix the comparison behaviour you may either change how you store numbers (but given the field you used them I doubt that's a good idea) or change how you compare them: give room for an epsilon 'error' difference between two numbers. If you do not want to implement your own way to do it, you may use numpy/math isclose for checking equality like this:
import numpy as np
p = 0.6
for i in np.arange(0,1.1,0.1):
if p > i or np.isclose(p,i):
print('yes for i = %f' % i)
else:
print('no for i = %f' % i)
Depending on what you wish to do actually instead of the minimal example you gave, performing the comparisons in a single shot might be more efficient:
i = np.arange(0,1.1,0.1)
compres = np.logical_or(p>i, np.isclose(p,i))
for i, ge in zip(i, compres):
if ge:
print('yes for i = %.1f' % i)
else:
print('no for i = %.1f' % i)
EDIT:
I removed the idea of multiplying by 10000 and rounding before comparison, as it may lead to rounding errors at e.g. a 0.649999 vs. 0.650001 case. It can be useful, but with caution.