Re: Division-Bug in decimal and mpmath

Liste des GroupesRevenir à cl python 
Sujet : Re: Division-Bug in decimal and mpmath
De : oscar.j.benjamin (at) *nospam* gmail.com (Oscar Benjamin)
Groupes : comp.lang.python
Date : 15. Dec 2024, 22:29:18
Autres entêtes
Message-ID : <mailman.7.1734298172.2912.python-list@python.org>
References : 1 2 3
On Sat, 14 Dec 2024 at 19:02, Mark Bourne via Python-list
<python-list@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

Date Sujet#  Auteur
14 Dec 24 * Division-Bug in decimal and mpmath5Martin Ruppert
14 Dec 24 `* Re: Division-Bug in decimal and mpmath4Mark Bourne
14 Dec 24  +* Re: Division-Bug in decimal and mpmath22QdxY4RzWzUUiLuE
15 Dec 24  i`- Re: Division-Bug in decimal and mpmath1Mark Bourne
15 Dec 24  `- Re: Division-Bug in decimal and mpmath1Oscar Benjamin

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal