Message377906
Hi Leonard,
Any number which has only fixed precision will experience similar
issues. It might affect different calculations.
In Python, float, complex and Decimal have fixed precision, so they can
experience this issue.
But for simple calculations, Decimal may be better for you, as it uses
base-10 floats, not base-2, so many numbers which are rounded off in
binary floats are not rounded in Decimal:
py> from decimal import Decimal
py> 0.1111 + 0.2222 # binary floats
0.33330000000000004
py> Decimal('0.1111') + Decimal('0.2222') # decimal floats
Decimal('0.3333')
But with Decimal, you have other numbers which are rounded off and so
are not exact:
py> one_third = 1/Decimal(3)
py> 3*one_third # should be exactly 1
Decimal('0.9999999999999999999999999999')
py> (1/Decimal(6)) * 3
Decimal('0.5000000000000000000000000001')
ints are always exact, but you can only do whole numbers with ints.
Fractions are also exact:
py> from fractions import Fraction
py> Fraction(1111, 10000) + Fraction(2222, 10000)
Fraction(3333, 10000)
Using Fraction is a good way to see what number a binary float really
is:
py> Fraction(0.1111)
Fraction(4002799348806897, 36028797018963968) |
|
Date |
User |
Action |
Args |
2020-10-03 23:24:10 | steven.daprano | set | recipients:
+ steven.daprano, ungedummt |
2020-10-03 23:24:10 | steven.daprano | link | issue41920 messages |
2020-10-03 23:24:10 | steven.daprano | create | |
|