Code Explanation:
1) from fractions import Fraction
Imports the Fraction class from Python’s standard fractions module.
Fraction represents rational numbers exactly as numerator/denominator (no binary floating error).
Use it when you need exact rational arithmetic instead of floats.
2) f1 = Fraction(2, 3)
Creates a Fraction object representing 2/3.
Internally stored as numerator 2 and denominator 3.
type(f1) is fractions.Fraction.
3) f2 = Fraction(3, 4)
Creates a second Fraction object representing 3/4.
Internally numerator 3, denominator 4.
4) result = f1 + f2
Adds the two fractions exactly (rational addition).
Calculation shown stepwise:
Convert to common denominator: 2/3 = 8/12, 3/4 = 9/12.
Add: 8/12 + 9/12 = 17/12.
result is a Fraction(17, 12) (17/12). This is already in lowest terms.
5) print(result, float(result))
print(result) displays the Fraction in string form: "17/12".
float(result) converts the rational 17/12 to a floating-point approximation: 1.4166666666666667.
The decimal is approximate because float uses binary floating point.
Final printed output
17/12 1.4166666666666667
.png)

0 Comments:
Post a Comment