on floating-point numbers

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Sep 4 11:38:55 EDT 2021


On 5/09/21 2:42 am, Hope Rouselle wrote:
> Here's what I did on this case.  The REPL is telling me that
> 
>    7.23 = 2035064081618043/281474976710656

If 7.23 were exactly representable, you would have got
723/1000.

Contrast this with something that *is* exactly representable:

 >>> 7.875.as_integer_ratio()
(63, 8)

and observe that 7875/1000 == 63/8:

 >>> from fractions import Fraction
 >>> Fraction(7875,1000)
Fraction(63, 8)

In general, to find out whether a decimal number is exactly
representable in binary, represent it as a ratio of integers
where the denominator is a power of 10, reduce that to lowest
terms, and compare with the result of as_integer_ratio().

-- 
Greg


More information about the Python-list mailing list