pythonpython-3.xfractionspython-fractions

what is the difference between the Fraction class constructor and from_float in Python


I am using the class constructor Fraction to create fractions. What is the difference between using the Fraction class constructor and from_float method when creating fractions from floating-point numbers?

I tested it with different numbers and I got same answers. for instance:

from fractions import Fraction

f1 = Fraction(0.3)
f2 = Fraction.from_float(0.3)

print(f1)  # Output: 5404319552844595/18014398509481984
print(f2)  # Output: 5404319552844595/18014398509481984

Solution

  • From the documentation:

    Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances.

    Note: From Python 3.2 onwards, you can also construct a Fraction instance directly from a float.

    In other words, in Python < 3.2, you had to use Fraction.from_float to construct a Fraction from a float. Since 3.2 this has become unnecessary, but still exists probably so as not to break backwards compatibility. You may also want to use it for more explicit type checking, as Fraction.from_float would raise an error if you passed some other type, which the Fraction constructor might silently accept and potentially lead to subtle bugs.