Why fractions.Fraction (1/3) does not return "1/3"?

6
import fractions
a = int(input())
b = 1 / a
b = fractions.Fraction(b)
print(b)

This is part of a code I'm developing. This part had the function of taking the decimal resulting from the division "1 / a" and transforming it into fraction and apparently is not working. Ex:

input = 3

b = 1/3 = 0.333

b = 1/3 (Desired Output)

But the output I get with this example is "6004799503160661/18014398509481984". I know this is an equivalent fraction but the "1/3" fraction would be enough.

    
asked by anonymous 03.01.2019 / 18:45

1 answer

7

1/3 is a periodic tithing; that is, the amount of 3 after the comma is infinite, which makes it impossible to represent it computationally. When you store the value in memory, the value will be truncated according to the architecture you are using, so the fraction representation is no longer 1/3.

Notice that the inconsistency is very explicit even in your example, where it says "1/3 = 0.333". Mathematically, 1/3 is worth 0.33333333333 ..., not just 0.333. They are different numbers, with different generative fractions.

But the main point is: why divide before generating the fraction?

When you read documentation you will see that Fraction receives two parameters: the numerator and the denominator. That is, just do:

import fractions

a = int(input())
b = fractions.Fraction(1, a)

print(b)

If you enter the value 3, the output will be 1/3.

Notice that the same problem happens in other values, even if they do not generate a periodic tithing. For example, in your code, if you enter the value 5, which should generate the value 0.2, and consequently returning the fraction 1/5 actually returns 3602879701896397/18014398509481984. This is because, similar to what was commented above, the value 1/5 also can not be represented as floating point. The value that looks like 0.2 is actually a value very close to it, which causes the generated fraction to be different than expected.

For more details, read:

03.01.2019 / 19:01