Reading the documentation

Chris Angelico rosuav at gmail.com
Fri Aug 25 02:12:09 EDT 2017


On Fri, Aug 25, 2017 at 4:03 PM, Steve D'Aprano
<steve+python at pearwood.info> wrote:
> On Fri, 25 Aug 2017 03:22 pm, Chris Angelico wrote:
>
>>> py> from decimal import Decimal
>>> py> sum([1/13]*13)
>>> 0.9999999999999998
>>> py> sum([Decimal(1)/Decimal(13)]*13)
>>> Decimal('0.9999999999999999999999999997')
>>
>> Now do the same exercise with pencil and paper. What's 1/13?
>
> Easy: 0.(076923) where the brackets surround the digits which repeat.
>
> I'm not so good at division in binary, but I *think* it should be:
>
> 0b0.(000100111011)
>
> where, again, the repeating bits are in brackets.
>
>
> [...]
>> Two sevenths is 0.285714285714.
>
> No it isn't. The decimal is repeating, so its actually 0.(285714). By truncating
> it to only a finite number of decimal places, you introduce some rounding
> error.

Ask someone to write it down on a piece of paper. I can pretty much
guarantee that they'll truncate or round.

> And there are numbers which repeat in decimal but not binary, and numbers which
> repeat in both, and numbers which don't repeat in either.

Which ones repeat in decimal but not binary? An example, please.

Ones which repeat in neither are easy. Ones which repeat in both are
usually not confusing, as it's easy to explain how the truncation
works.

ChrisA



More information about the Python-list mailing list