The from_float
method obtains an instance of the Fraction
class where the numerator and the denominator are inferred for the given floating-point value.
We also create a Fraction
object by explicitly specifying the numerator and the denominator. However, this object is not the same as the one created using the from_float
method.
For example:
Fraction.from_float(0.2) != Fraction(2, 10)
from_float(flt)
flt
: This is a floating-point value.The return type is a Fraction
object.
import fractionsfloat_value = 0.2fraction_object_1 = fractions.Fraction.from_float(float_value)fraction_object_2 = fractions.Fraction(2, 10)print("Fraction object using from_float method - %s" % (fraction_object_1))print("Fraction object by specifying numerator and denominator - %s" % (fraction_object_2))
Line 1: We import the fractions
module.
Line 3: We define a floating-point called float_value
.
Line 5: We create an instance of the Fraction
class called fraction_object_1
using the from_float
method.
Line 7: We create an instance of the Fraction
class called fraction_object_2
by passing the numerator and denominator values as constructor arguments.
Lines 9-11: We print fraction_object_1
and fraction_object_2
.
From the output, we can conclude Fraction.from_float(0.2) != Fraction(2, 10)
.