Like Pedro said, it’s not a Python bug.
If you know that the increment will always be 0.2
(or any fixed number), you can simply store the values multiplied by 5
(the multiplicative inverse of the increment) as integrates and divide by 5.0
when you need the value as float
. This avoids problems with a rounding error.
As requested, a simple example:
J1, J2, J3, I = 5, 10, 15, 0
while I <= 10:
print( 'I={} J={}'.format(I/5.0, J1/5.0) )
print( 'I={} J={}'.format(I/5.0, J2/5.0) )
print( 'I={} J={}'.format(I/5.0, J3/5.0) )
J1 += 1
J2 += 1
J3 += 1
I += 1
With a result of:
I=0.0 J=1.0
I=0.0 J=2.0
I=0.0 J=3.0
I=0.2 J=1.2
I=0.2 J=2.2
I=0.2 J=3.2
I=0.4 J=1.4
I=0.4 J=2.4
I=0.4 J=3.4
I=0.6 J=1.6
I=0.6 J=2.6
I=0.6 J=3.6
I=0.8 J=1.8
I=0.8 J=2.8
I=0.8 J=3.8
I=1.0 J=2.0
I=1.0 J=3.0
I=1.0 J=4.0
I=1.2 J=2.2
I=1.2 J=3.2
I=1.2 J=4.2
I=1.4 J=2.4
I=1.4 J=3.4
I=1.4 J=4.4
I=1.6 J=2.6
I=1.6 J=3.6
I=1.6 J=4.6
I=1.8 J=2.8
I=1.8 J=3.8
I=1.8 J=4.8
I=2.0 J=3.0
I=2.0 J=4.0
I=2.0 J=5.0
It would probably be better to encapsulate the code to do division multiplication within a class, but I don’t know Python so much to give a good example of this.
Also I have heard of classes that keep fractions instead of floating points to keep (almost) any rational number without losing precision.
I think the class Decimal
of Python already does something similar to what I am describing, but quarda an integro number and keeps a power of ten to make the division (or multiplication). So I guess Decimal
is similar to floating point, but with powers of ten instead of powers of two.
If it’s just a display issue, you can format the output with
{:.2}
, limiting thus only two decimal places. If used for mathematical operations, use the moduledecimal
as already answered.– Woss
Related: https://answall.com/q/219211/64969
– Jefferson Quesado
In this answer I show an example calculation with a class of numbers that shares the same problem of floating point numbers: https://answall.com/a/272376/64969
– Jefferson Quesado
Related: https://answall.com/q/273728/64969
– Jefferson Quesado
Read Floating-point arithmetic: problems and limitations.
– Solkarped