2

I have a simple code, written to simplify fractions in python. Putting in certain numbers (Such as shown in the code) give huge, and possibly incorrect values. Below is the code.

from fractions import Fraction
print(Fraction(36/40))

And it outputs:

8106479329266893/9007199254740992

Why does it do this, and how can I fix this?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • I'm going to guess it's just a floating point error? http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – jhaagsma Oct 21 '16 at 23:04

1 Answers1

2

I believe that you intended to use Fraction(36, 40). Notice the comma instead of the slash. What happens is that you input a division result instead of the numerator and denominator.

There are quite a few ways to init the Fraction. Take a look at the docs.

Dmitry Yantsen
  • 1,145
  • 11
  • 24
  • Does the docs article you have linked contain info over / vs , and other related things? – Daniel La Cour Oct 21 '16 at 23:14
  • It's right at the beginning. Basically you can initialize the Fraction with two integer numbers (which I suggested), another fraction, a float number (which was unintentionally your case), a decimal number or a string. String will actually just get parsed to two integers. – Dmitry Yantsen Oct 21 '16 at 23:18
  • 1
    @DanielLaCour The difference is in which constructor is called. Since a comma delimits function arguments, with a comma, you're supplying 2 arguments. With a slash, you're supplying 1 argument, which is the result of division. – Carcigenicate Oct 21 '16 at 23:34