Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #197069

Re: Division-Bug in decimal and mpmath

From Oscar Benjamin <oscar.j.benjamin@gmail.com>
Newsgroups comp.lang.python
Subject Re: Division-Bug in decimal and mpmath
Date 2024-12-15 21:29 +0000
Message-ID <mailman.7.1734298172.2912.python-list@python.org> (permalink)
References <vjjcnl$3tdnk$1@dont-email.me> <vjjsfu$5jc$1@dont-email.me> <CAHVvXxTyu0BWGjnYHR6eSdvTj+1EQACT67SW2hb-q0Q_MvU-mg@mail.gmail.com>

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar


Thread

Division-Bug in decimal and mpmath Martin Ruppert <ruppert@hs-worms.de> - 2024-12-14 07:39 +0000
  Re: Division-Bug in decimal and mpmath Mark Bourne <nntp.mbourne@spamgourmet.com> - 2024-12-14 12:08 +0000
    Re: Division-Bug in decimal and mpmath 2QdxY4RzWzUUiLuE@potatochowder.com - 2024-12-14 14:21 -0500
      Re: Division-Bug in decimal and mpmath Mark Bourne <nntp.mbourne@spamgourmet.com> - 2024-12-15 11:59 +0000
    Re: Division-Bug in decimal and mpmath Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2024-12-15 21:29 +0000

csiph-web