[Tutor] Accessing a tuple of a dictionary's value

Steven D'Aprano steve at pearwood.info
Wed Aug 22 07:35:23 EDT 2018


On Tue, Aug 21, 2018 at 03:27:46PM -0700, Roger Lea Scherer wrote:

> So I'm trying to divide fractions, technically I suppose integers.

Python has a library for doing maths with fractions. Unfortunately it is 
considerably too complex to use as a learning example, but as a 
practical library for use, it's great.

py> from fractions import Fraction
py> a = Fraction(7, 9)
py> a * 3
Fraction(7, 3)
py> a + 2
Fraction(25, 9)
py> a - Fraction(1, 9)
Fraction(2, 3)


> So, for
> instance, when the user inputs a 1 as the numerator and a 2 as the
> denominator to get the float 0.5, I want to put the 0.5 as the key in a
> dictionary 

Be careful. Floats are quirky:

py> Fraction(1, 3)
Fraction(1, 3)

but converting from a float reveals something strange:

py> Fraction(1/3)
Fraction(6004799503160661, 18014398509481984)

The problem is that the float generated by 1/3 is *not* equal to the 
mathematical fraction 1 over 3. Computer floats have only a finite 
precision, in the case of Python 64 bits. Fractions which are repeating 
in binary cannot be represented as an exact float.

So the mathematically precise number 1/3 looks like this is decimal:

    0.33333333...  # need an infinite number of 3s

and like this in binary (base two):

    0.01010101...  # need an infinite number of 01s

Since that would take an infinite amount of memory, it is impossible to 
store 1/3 as a floating point number. The closest we get in Python is 

    0.01010101010101010101010101010101010101010101010101 (binary)

which is precisely and exactly equal to 

    6004799503160661/18014398509481984

rather than 1/3.

The bottom line is this: if you try working with floats in this way, 
you're likely to get surprised from time to time. See here for more 
detail:

https://docs.python.org/3/faq/design.html#why-are-floating-point-calculations-so-inaccurate

More to follow in a second response.



-- 
Steve


More information about the Tutor mailing list