Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading