Division-Bug in decimal and mpmath
Oscar Benjamin
oscar.j.benjamin at gmail.com
Sun Dec 15 16:29:18 EST 2024
On Sat, 14 Dec 2024 at 19:02, Mark Bourne via Python-list
<python-list at python.org> wrote:
>
> Martin Ruppert wrote:
> > Hi,
> >
> > the division 0.4/7 provides a wrong result. It should give a periodic
> > decimal fraction with at most six digits, but it doesn't.
> >
> > Below is the comparison of the result of decimal, mpmath, dc and calc.
...
>
> I looks like you might be running into limitations in floating-point
> numbers. At least with decimal, calculating 4/70 instead of 0.4/7
> appears to give the correct result. As does:
> ```
> from decimal import Decimal as dec
> z2 = dec(4) / dec(10)
> print(z2 / dec(nen))
> ```
> You can also pass a string, and `dec("0.4")/dec(10)` gives the correct
> result as well.
For completeness this is how to do it with mpmath:
>>> from mpmath import mp
>>> mp.dps = 60
>>> mp.mpf('0.4') / 7
mpf('0.0571428571428571428571428571428571428571428571428571428571428549')
You can also use SymPy:
>>> from sympy import Rational
>>> a = Rational('0.4') / 7
>>> a
2/35
>>> a.evalf(60)
0.0571428571428571428571428571428571428571428571428571428571429
SymPy uses mpmath for evalf but it allows doing exact calculations
first and then evaluating the final exact expression to however many
digits are desired at the end which means that you don't need to
accumulate rounding errors before calling evalf.
--
Oscar
More information about the Python-list
mailing list