[Tutor] the binary math "wall"

Jerry Hill malaclypse2 at gmail.com
Tue Apr 20 19:22:30 CEST 2010

On Tue, Apr 20, 2010 at 12:58 PM, Lowell Tackett
<lowelltackett at yahoo.com> wrote:
> Any of Python's help-aids that I apply to sort things out, such as formatting (%), or modules like "decimal" do nothing more than "powder up" the display for visual consumption (turning it into a string).  The underlying float value remains "corrupted", and any attempt to continue with the math adapts and re-incorporates the corruption.

Using the decimal module does not convert anything to strings.  The
decimal module gives you floating point arithmetic with base 10 rather
than base 2.

You examples seem to work okay for me using decimals:

IDLE 2.6.4
>>> import decimal
>>> n = decimal.Decimal("18.15")

>>> n

>>> print n

>>> divmod(n, 1)
(Decimal('18'), Decimal('0.15'))

>>> divmod(divmod(n, 1)[1]*100, 1)[1]/decimal.Decimal("0.6")

If you need to avoid floating point calculations entirely, you might
try the fractions module (new in python 2.6):

>>> import fractions
>>> n = fractions.Fraction("18.15")

>>> n
Fraction(363, 20)

>>> print n

>>> divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6")
Fraction(0, 1)

>>> print divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6")

and if you need to convert to float at the end:

>>> float(divmod(divmod(n, 1)[1]*100, 1)[1]/fractions.Fraction("0.6"))


More information about the Tutor mailing list