Reading the documentation

Steve D'Aprano steve+python at pearwood.info
Fri Aug 25 09:01:28 EDT 2017


On Fri, 25 Aug 2017 04:12 pm, Chris Angelico wrote:

>> 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.

What? No. I never said that, that would be silly. You must be replying to some
other Steven.

*wink*

Quoting Wikipedia:

"A rational number has a terminating sequence after the radix point if all the
prime factors of the denominator of the fully reduced fractional form are also
factors of the base. [...]

A rational number has an infinitely repeating sequence of [digits] if the
reduced fraction's denominator contains a prime factor that is not a factor of
the base."

https://en.wikipedia.org/wiki/Repeating_decimal#Extension_to_other_bases


Fractions will terminate in decimal if their denominator is a power of two, a
power of five, or a multiple of such, e.g.:

    2, 4, 8, 16, 32, 64, ...
    5, 25, 125, 625, ...
    10, 20, 40, 50, 80, 100, ...

and will terminate in binary if their denominator is:

    2, 4, 8, 16, 32, ...

so obviously any number which terminates in binary will also terminate in
decimal, but not necessarily vice versa.

Fractions will repeat in decimal if their denominator is a multiple of any of
the following primes:

    3, 7, 11, 13, 17, ... 

and fractions will repeat in binary if their denominator is a multiple of:

    3, 5, 7, 11, 13, 17, ...

so clearly any number which repeats in decimal will also repeat in binary. Like
I said.[1]



How did we get onto prime factors of denominators? The point I was making is
that there are plenty of fractions which are not multiples of 1/5 which
nevertheless lead to unintuitive "wrong answers" in both Decimal and binary
floating point. It is not necessary for the fraction to have a denominator
which is a multiple of 5 to run into issues.





[1] Just now. What may have been said in the past is the past, and long
forgotten. *wink*

-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list