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

Asked

Viewed 295 times

6

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

This is a piece of code I’m developing. This part had the function of taking the decimal resulting from the division "1 / a" and transforming it into a fraction and apparently 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.

1 answer

8


1/3 is a periodic tithe; 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.

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

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

When reading the documentation will see that Fraction takes 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 3, the output will be 1/3.

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

For more details read:

  • I checked here, and this is really the problem, divisions that do not return dizimas are in their simplified form. I know that 1/3 = 0.333... kkkkk. I used the structure you recommended and it worked, thank you very much. Ps: I’ve never used this module before, I’m learning to use it yet.

  • @Gustavomatias then I recommend that you read the documentation before continuing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.