Math & Numbers
Fractions Introduction
Recipes, measurements, and mathematical calculations often involve exact ratios that lose precision when converted to decimals. The Fraction module represents rational numbers as numerator/denominator pairs, automatically simplifying results and maintaining perfect accuracy.
Fraction
A numeric type representing exact rational numbers as a ratio of two integers, with automatic simplification to lowest terms.
Creating Fractions
Multiple ways to create fraction objects:
create.py
Replay: real traced execution (multi-file project)
# Create Fraction
from fractions import Fraction
import math
# Create Fraction
print("Create Fraction:")
# From integers (numerator, denominator)
f1 = Fraction(3, 4)
print(f"From ints (3, 4): {f1}")
# From float
f2 = Fraction(0.75)
print(f"From float (0.75): {f2}")
# From string
f3 = Fraction('3/4')
print(f"From string ('3/4'): {f3}")
f4 = Fraction('0.75')
print(f"From string ('0.75'): {f4}")
# From Decimal
from decimal import Decimal
d = Decimal('0.75')
f5 = Fraction(d)
print(f"From Decimal: {f5}")
# Whole numbers
f6 = Fraction(5)
print(f"From int (5): {f6}")
# Negative fractions
f7 = Fraction(-3, 4)
print(f"Negative (-3, 4): {f7}")
f8 = Fraction(3, -4)
print(f"Negative (3, -4): {f8}")
# Automatic simplification
print("\nAutomatic simplification:")
f9 = Fraction(6, 8)
print(f"6/8 simplified: {f9}")
f10 = Fraction(12, 16)
print(f"12/16 simplified: {f10}")
f11 = Fraction(100, 200)
print(f"100/200 simplified: {f11}")
# Numerator and denominator
print("\nNumerator and denominator:")
f = Fraction(3, 4)
print(f"Fraction: {f}")
print(f"Numerator: {f.numerator}")
print(f"Denominator: {f.denominator}")
# Zero
print("\nZero:")
zero = Fraction(0)
print(f"Zero: {zero}")
print(f"Numerator: {zero.numerator}")
print(f"Denominator: {zero.denominator}")
# From float (precision note)
print("\nFrom float (precision):")
f12 = Fraction(0.1)
print(f"Fraction(0.1): {f12}") # Shows float precision issues
f13 = Fraction('0.1')
print(f"Fraction('0.1'): {f13}") # Exact
# limit_denominator
print("\nlimit_denominator:")
f14 = Fraction(0.1)
print(f"Original: {f14}")
print(f"Limited to 10: {f14.limit_denominator(10)}")
print(f"Limited to 100: {f14.limit_denominator(100)}")
# Approximate pi
print("\nApproximate pi:")
pi_frac = Fraction(str(math.pi))
print(f"Pi as fraction: {pi_frac}")
print(f"Pi limited to 1000: {pi_frac.limit_denominator(1000)}")
print(f"Pi limited to 100: {pi_frac.limit_denominator(100)}")
# from_float and from_decimal
print("\nfrom_float and from_decimal:")
f15 = Fraction.from_float(0.75)
print(f"from_float(0.75): {f15}")
f16 = Fraction.from_decimal(Decimal('0.75'))
print(f"from_decimal('0.75'): {f16}")
# Convert to other types
print("\nConvert to other types:")
f = Fraction(3, 4)
print(f"Fraction: {f}")
print(f"float: {float(f)}")
print(f"int (truncate): {int(f)}")
print(f"Decimal: {Decimal(f.numerator) / Decimal(f.denominator)}")
# Common fractions
print("\nCommon fractions:")
fractions = [
(1, 2), (1, 3), (1, 4), (1, 5),
(2, 3), (3, 4), (3, 5), (4, 5)
]
for num, den in fractions:
f = Fraction(num, den)
print(f"{num}/{den} = {f} = {float(f):.4f}")
f1 ← 3/4, f2 ← 3/4, f3 ← 3/4, f4 ← 3/4, d ← 0.75, f5 ← 3/4, f6 ← 5
6# Create Fraction7print("Create Fraction:")89# From integers (numerator, denominator)10f1→ 3/4 = Fraction(3, 4)11print(f"From ints (3, 4): {f13/4}")1213# From float14f2→ 3/4 = Fraction(0.75)15print(f"From float (0.75): {f23/4}")1617# From string18f3→ 3/4 = Fraction('3/4')19print(f"From string ('3/4'): {f33/4}")2021f4→ 3/4 = Fraction('0.75')22print(f"From string ('0.75'): {f43/4}")2324# From Decimal25from decimal import Decimal26d→ 0.75 = Decimal('0.75')27f5→ 3/4 = Fraction(d0.75)28print(f"From Decimal: {f53/4}")2930# Whole numbers31f6→ 5 = Fraction(5)32print(f"From int (5): {f65}")3334# Negative fractions35f7→ -3/4 = Fraction(-3, 4)36print(f"Negative (-3, 4): {f7-3/4}")3738f8→ -3/4 = Fraction(3, -4)39print(f"Negative (3, -4): {f8-3/4}")4041# Automatic simplification42print("\nAutomatic simplification:")43f9→ 3/4 = Fraction(6, 8)44print(f"6/8 simplified: {f93/4}")4546f10→ 3/4 = Fraction(12, 16)47print(f"12/16 simplified: {f103/4}")4849f11→ 1/2 = Fraction(100, 200)50print(f"100/200 simplified: {f111/2}")5152# Numerator and denominator53print("\nNumerator and denominator:")54f→ 3/4 = Fraction(3, 4)55print(f"Fraction: {f3/4}")56print(f"Numerator: {f.numerator3}")57print(f"Denominator: {f.denominator4}")5859# Zero60print("\nZero:")61zero→ 0 = Fraction(0)62print(f"Zero: {zero0}")63print(f"Numerator: {zero.numerator0}")64print(f"Denominator: {zero.denominator1}")6566# From float (precision note)67print("\nFrom float (precision):")68f12→ 3602879701896397/36028797018963968 = Fraction(0.1)69print(f"Fraction(0.1): {f123602879701896397/36028797018963968}") # Shows float precision issues7071f13→ 1/10 = Fraction('0.1')72print(f"Fraction('0.1'): {f131/10}") # Exact7374# limit_denominator75print("\nlimit_denominator:")76f14→ 3602879701896397/36028797018963968 = Fraction(0.1)77print(f"Original: {f143602879701896397/36028797018963968}")78print(f"Limited to 10: {f143602879701896397/36028797018963968.limit_denominator(10)}")79print(f"Limited to 100: {f143602879701896397/36028797018963968.limit_denominator(100)}")8081# Approximate pi82print("\nApproximate pi:")83pi_frac→ 3141592653589793/1000000000000000 = Fraction(str(math.pi3.141592653589793))84print(f"Pi as fraction: {pi_frac3141592653589793/1000000000000000}")85print(f"Pi limited to 1000: {pi_frac3141592653589793/1000000000000000.limit_denominator(1000)}")86print(f"Pi limited to 100: {pi_frac3141592653589793/1000000000000000.limit_denominator(100)}")8788# from_float and from_decimal89print("\nfrom_float and from_decimal:")90f15→ 3/4 = Fraction<class 'fractions.Fraction'>.from_float(0.75)91print(f"from_float(0.75): {f153/4}")9293f16→ 3/4 = Fraction<class 'fractions.Fraction'>.from_decimal(Decimal('0.75'))94print(f"from_decimal('0.75'): {f163/4}")9596# Convert to other types97print("\nConvert to other types:")98f→ 3/4 = Fraction(3, 4)99print(f"Fraction: {f3/4}")100print(f"float: {float(f3/4)}")101print(f"int (truncate): {int(f3/4)}")102print(f"Decimal: {Decimal(f.numerator3) / Decimal(f.denominator4)}")103104# Common fractions105print("\nCommon fractions:")106fractions→ [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (3, 4), (3, 5), (4, 5)] = [107 (1, 2), (1, 3), (1, 4), (1, 5),108 (2, 3), (3, 4), (3, 5), (4, 5)109]110for num, den in fractions:outputCreate Fraction: From ints (3, 4): 3/4 From float (0.75): 3/4 From string ('3/4'): 3/4 From string ('0.75'): 3/4 From Decimal: 3/4 From int (5): 5 Negative (-3, 4): -3/4 Negative (3, -4): -3/4 Automatic simplification: 6/8 simplified: 3/4 12/16 simplified: 3/4 100/200 simplified: 1/2 Numerator and denominator: Fraction: 3/4 Numerator: 3 Denominator: 4 Zero: Zero: 0 Numerator: 0 Denominator: 1 From float (precision): Fraction(0.1): 3602879701896397/36028797018963968 Fraction('0.1'): 1/10 limit_denominator: Original: 3602879701896397/36028797018963968 Limited to 10: 1/10 Limited to 100: 1/10 Approximate pi: Pi as fraction: 3141592653589793/1000000000000000 Pi limited to 1000: 355/113 Pi limited to 100: 311/99 from_float and from_decimal: from_float(0.75): 3/4 from_decimal('0.75'): 3/4 Convert to other types: Fraction: 3/4 float: 0.75 int (truncate): 0 Decimal: 0.75 Common fractions:f ← 1/2
pass 1 of 8109]110for num1, den2 in fractions[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (3, 4), (3, 5), (4, 5)]:111 f→ 1/2 = Fraction(num1, den2)112 print(f"{num1}/{den2} = {f1/2} = {float(f):.4f}")output1/2 = 1/2 = 0.5000All 8 passes — pass 1 is the card above pass numdenf1 1 2 1/2 2 1 3 1/3 3 1 4 1/4 4 1 5 1/5 5 2 3 2/3 6 3 4 3/4 7 3 5 3/5 8 4 5 4/5
automatic simplification
Fractions automatically reduce to lowest terms - Fraction(6, 8) becomes Fraction(3, 4).
Arithmetic Operations
Fractions support all standard math operations:
arithmetic.py
Replay: real traced execution (multi-file project)
# Arithmetic operations
from fractions import Fraction
# Arithmetic
a = Fraction(3, 4)
b = Fraction(2, 5)
print(f"a = {a}")
print(f"b = {b}")
print()
# Addition
print("Addition:")
print(f"a + b = {a + b}")
print(f" = {a.numerator * b.denominator + b.numerator * a.denominator}/{a.denominator * b.denominator}")
# Subtraction
print("\nSubtraction:")
print(f"a - b = {a - b}")
# Multiplication
print("\nMultiplication:")
print(f"a * b = {a * b}")
print(f" = {a.numerator * b.numerator}/{a.denominator * b.denominator}")
# Division
print("\nDivision:")
print(f"a / b = {a / b}")
print(f" = {a.numerator * b.denominator}/{a.denominator * b.numerator}")
# Floor division
print("\nFloor division:")
print(f"a // b = {a // b}")
# Modulo
print("\nModulo:")
print(f"a % b = {a % b}")
# Power
print("\nPower:")
f = Fraction(2, 3)
print(f"{f}^2 = {f ** 2}")
print(f"{f}^3 = {f ** 3}")
print(f"{f}^-1 = {f ** -1}") # Reciprocal
# Negation
print("\nNegation:")
print(f"-a = {-a}")
# Absolute value
print("\nAbsolute value:")
neg = Fraction(-3, 4)
print(f"abs({neg}) = {abs(neg)}")
# Reciprocal
print("\nReciprocal:")
f = Fraction(3, 4)
print(f"Reciprocal of {f} = {1 / f}")
print(f" = {Fraction(f.denominator, f.numerator)}")
# Mixed operations
print("\nMixed operations:")
print(f"Fraction + int: {a + 2}")
print(f"int + Fraction: {2 + a}")
print(f"Fraction * int: {a * 3}")
print(f"Fraction / int: {a / 2}")
# Chaining
print("\nChaining:")
result = Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6)
print(f"1/2 + 1/3 + 1/6 = {result}")
# Complex expression
print("\nComplex expression:")
expr = (Fraction(3, 4) * Fraction(2, 5) + Fraction(1, 2)) / Fraction(3, 8)
print(f"(3/4 * 2/5 + 1/2) / 3/8 = {expr}")
# Sum of series
print("\nSum of series:")
# 1/1 + 1/2 + 1/3 + 1/4 + 1/5
series_sum = sum(Fraction(1, i) for i in range(1, 6))
print(f"1/1 + 1/2 + 1/3 + 1/4 + 1/5 = {series_sum}")
print(f" = {float(series_sum):.6f}")
# Harmonic series
print("\nHarmonic series (first 10 terms):")
harmonic = sum(Fraction(1, i) for i in range(1, 11))
print(f"H_10 = {harmonic}")
print(f" ≈ {float(harmonic):.10f}")
# Factorial fractions
print("\nFactorial fractions:")
# 1/1! + 1/2! + 1/3! + 1/4!
import math
factorial_sum = sum(Fraction(1, math.factorial(i)) for i in range(1, 5))
print(f"1/1! + 1/2! + 1/3! + 1/4! = {factorial_sum}")
print(f" = {float(factorial_sum):.10f}")
print(f" (approaching e-1 = {math.e - 1:.10f})")
# Dividing whole cake
print("\nDividing cake:")
cake = Fraction(1) # Whole cake
people = 8
slice_size = cake / people
print(f"Cake for {people} people: {slice_size} each")
print(f"3 people get: {slice_size * 3}")
# Recipe scaling
print("\nRecipe scaling:")
original = Fraction(2, 3) # 2/3 cup
scale_factor = Fraction(3, 2) # 1.5x recipe
scaled = original * scale_factor
print(f"Original: {original} cup")
print(f"Scaled by {scale_factor}: {scaled} cup")
print(f" = {float(scaled)} cup")
# Arithmetic operations
from fractions import Fraction
# Arithmetic
a = Fraction(3, 4)
b = Fraction(2, 5)
print(f"a = {a}")
print(f"b = {b}")
print()
# Addition
print("Addition:")
print(f"a + b = {a + b}")
print(f" = {a.numerator * b.denominator + b.numerator * a.denominator}/{a.denominator * b.denominator}")
# Subtraction
print("\nSubtraction:")
print(f"a - b = {a - b}")
# Multiplication
print("\nMultiplication:")
print(f"a * b = {a * b}")
print(f" = {a.numerator * b.numerator}/{a.denominator * b.denominator}")
# Division
print("\nDivision:")
print(f"a / b = {a / b}")
print(f" = {a.numerator * b.denominator}/{a.denominator * b.numerator}")
# Floor division
print("\nFloor division:")
print(f"a // b = {a // b}")
# Modulo
print("\nModulo:")
print(f"a % b = {a % b}")
# Power
print("\nPower:")
f = Fraction(2, 3)
print(f"{f}^2 = {f ** 2}")
print(f"{f}^3 = {f ** 3}")
print(f"{f}^-1 = {f ** -1}") # Reciprocal
# Negation
print("\nNegation:")
print(f"-a = {-a}")
# Absolute value
print("\nAbsolute value:")
neg = Fraction(-3, 4)
print(f"abs({neg}) = {abs(neg)}")
# Reciprocal
print("\nReciprocal:")
f = Fraction(3, 4)
print(f"Reciprocal of {f} = {1 / f}")
print(f" = {Fraction(f.denominator, f.numerator)}")
# Mixed operations
print("\nMixed operations:")
print(f"Fraction + int: {a + 2}")
print(f"int + Fraction: {2 + a}")
print(f"Fraction * int: {a * 3}")
print(f"Fraction / int: {a / 2}")
# Chaining
print("\nChaining:")
result = Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6)
print(f"1/2 + 1/3 + 1/6 = {result}")
# Complex expression
print("\nComplex expression:")
expr = (Fraction(3, 4) * Fraction(2, 5) + Fraction(1, 2)) / Fraction(3, 8)
print(f"(3/4 * 2/5 + 1/2) / 3/8 = {expr}")
# Sum of series
print("\nSum of series:")
# 1/1 + 1/2 + 1/3 + 1/4 + 1/5
series_sum = sum(Fraction(1, i) for i in range(1, 6))
print(f"1/1 + 1/2 + 1/3 + 1/4 + 1/5 = {series_sum}")
print(f" = {float(series_sum):.6f}")
# Harmonic series
print("\nHarmonic series (first 10 terms):")
harmonic = sum(Fraction(1, i) for i in range(1, 11))
print(f"H_10 = {harmonic}")
print(f" ≈ {float(harmonic):.10f}")
# Factorial fractions
print("\nFactorial fractions:")
# 1/1! + 1/2! + 1/3! + 1/4!
import math
factorial_sum = sum(Fraction(1, math.factorial(i)) for i in range(1, 5))
print(f"1/1! + 1/2! + 1/3! + 1/4! = {factorial_sum}")
print(f" = {float(factorial_sum):.10f}")
print(f" (approaching e-1 = {math.e - 1:.10f})")
# Dividing whole cake
print("\nDividing cake:")
cake = Fraction(1) # Whole cake
people = 4
slice_size = cake / people
print(f"Cake for {people} people: {slice_size} each")
print(f"3 people get: {slice_size * 3}")
# Recipe scaling
print("\nRecipe scaling:")
original = Fraction(2, 3) # 2/3 cup
scale_factor = Fraction(3, 2) # 1.5x recipe
scaled = original * scale_factor
print(f"Original: {original} cup")
print(f"Scaled by {scale_factor}: {scaled} cup")
print(f" = {float(scaled)} cup")
# Arithmetic operations
from fractions import Fraction
# Arithmetic
a = Fraction(3, 4)
b = Fraction(2, 5)
print(f"a = {a}")
print(f"b = {b}")
print()
# Addition
print("Addition:")
print(f"a + b = {a + b}")
print(f" = {a.numerator * b.denominator + b.numerator * a.denominator}/{a.denominator * b.denominator}")
# Subtraction
print("\nSubtraction:")
print(f"a - b = {a - b}")
# Multiplication
print("\nMultiplication:")
print(f"a * b = {a * b}")
print(f" = {a.numerator * b.numerator}/{a.denominator * b.denominator}")
# Division
print("\nDivision:")
print(f"a / b = {a / b}")
print(f" = {a.numerator * b.denominator}/{a.denominator * b.numerator}")
# Floor division
print("\nFloor division:")
print(f"a // b = {a // b}")
# Modulo
print("\nModulo:")
print(f"a % b = {a % b}")
# Power
print("\nPower:")
f = Fraction(2, 3)
print(f"{f}^2 = {f ** 2}")
print(f"{f}^3 = {f ** 3}")
print(f"{f}^-1 = {f ** -1}") # Reciprocal
# Negation
print("\nNegation:")
print(f"-a = {-a}")
# Absolute value
print("\nAbsolute value:")
neg = Fraction(-3, 4)
print(f"abs({neg}) = {abs(neg)}")
# Reciprocal
print("\nReciprocal:")
f = Fraction(3, 4)
print(f"Reciprocal of {f} = {1 / f}")
print(f" = {Fraction(f.denominator, f.numerator)}")
# Mixed operations
print("\nMixed operations:")
print(f"Fraction + int: {a + 2}")
print(f"int + Fraction: {2 + a}")
print(f"Fraction * int: {a * 3}")
print(f"Fraction / int: {a / 2}")
# Chaining
print("\nChaining:")
result = Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6)
print(f"1/2 + 1/3 + 1/6 = {result}")
# Complex expression
print("\nComplex expression:")
expr = (Fraction(3, 4) * Fraction(2, 5) + Fraction(1, 2)) / Fraction(3, 8)
print(f"(3/4 * 2/5 + 1/2) / 3/8 = {expr}")
# Sum of series
print("\nSum of series:")
# 1/1 + 1/2 + 1/3 + 1/4 + 1/5
series_sum = sum(Fraction(1, i) for i in range(1, 6))
print(f"1/1 + 1/2 + 1/3 + 1/4 + 1/5 = {series_sum}")
print(f" = {float(series_sum):.6f}")
# Harmonic series
print("\nHarmonic series (first 10 terms):")
harmonic = sum(Fraction(1, i) for i in range(1, 11))
print(f"H_10 = {harmonic}")
print(f" ≈ {float(harmonic):.10f}")
# Factorial fractions
print("\nFactorial fractions:")
# 1/1! + 1/2! + 1/3! + 1/4!
import math
factorial_sum = sum(Fraction(1, math.factorial(i)) for i in range(1, 5))
print(f"1/1! + 1/2! + 1/3! + 1/4! = {factorial_sum}")
print(f" = {float(factorial_sum):.10f}")
print(f" (approaching e-1 = {math.e - 1:.10f})")
# Dividing whole cake
print("\nDividing cake:")
cake = Fraction(1) # Whole cake
people = 12
slice_size = cake / people
print(f"Cake for {people} people: {slice_size} each")
print(f"3 people get: {slice_size * 3}")
# Recipe scaling
print("\nRecipe scaling:")
original = Fraction(2, 3) # 2/3 cup
scale_factor = Fraction(3, 2) # 1.5x recipe
scaled = original * scale_factor
print(f"Original: {original} cup")
print(f"Scaled by {scale_factor}: {scaled} cup")
print(f" = {float(scaled)} cup")
a ← 3/4, b ← 2/5, f ← 2/3, neg ← -3/4, result ← 1, expr ← 32/15
5# Arithmetic6a→ 3/4 = Fraction(3, 4)7b→ 2/5 = Fraction(2, 5)89print(f"a = {a3/4}")10print(f"b = {b2/5}")11print()1213# Addition14print("Addition:")15print(f"a + b = {a3/4 + b2/5}")16print(f" = {a.numerator3 * b.denominator5 + b.numerator2 * a.denominator4}/{a.denominator * b.denominator}")1718# Subtraction19print("\nSubtraction:")20print(f"a - b = {a3/4 - b2/5}")2122# Multiplication23print("\nMultiplication:")24print(f"a * b = {a3/4 * b2/5}")25print(f" = {a.numerator3 * b.numerator2}/{a.denominator4 * b.denominator5}")2627# Division28print("\nDivision:")29print(f"a / b = {a3/4 / b2/5}")30print(f" = {a.numerator3 * b.denominator5}/{a.denominator4 * b.numerator2}")3132# Floor division33print("\nFloor division:")34print(f"a // b = {a3/4 // b2/5}")3536# Modulo37print("\nModulo:")38print(f"a % b = {a3/4 % b2/5}")3940# Power41print("\nPower:")42f→ 2/3 = Fraction(2, 3)43print(f"{f2/3}^2 = {f ** 2}")44print(f"{f2/3}^3 = {f ** 3}")45print(f"{f2/3}^-1 = {f ** -1}") # Reciprocal4647# Negation48print("\nNegation:")49print(f"-a = {-a3/4}")5051# Absolute value52print("\nAbsolute value:")53neg→ -3/4 = Fraction(-3, 4)54print(f"abs({neg-3/4}) = {abs(neg)}")5556# Reciprocal57print("\nReciprocal:")58f→ 3/4 = Fraction(3, 4)59print(f"Reciprocal of {f3/4} = {1 / f}")60print(f" = {Fraction(f.denominator4, f.numerator3)}")6162# Mixed operations63print("\nMixed operations:")64print(f"Fraction + int: {a3/4 + 2}")65print(f"int + Fraction: {2 + a3/4}")66print(f"Fraction * int: {a3/4 * 3}")67print(f"Fraction / int: {a3/4 / 2}")6869# Chaining70print("\nChaining:")71result→ 1 = Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6)72print(f"1/2 + 1/3 + 1/6 = {result1}")7374# Complex expression75print("\nComplex expression:")76expr→ 32/15 = (Fraction(3, 4) * Fraction(2, 5) + Fraction(1, 2)) / Fraction(3, 8)77print(f"(3/4 * 2/5 + 1/2) / 3/8 = {expr32/15}")7879# Sum of series80print("\nSum of series:")81# 1/1 + 1/2 + 1/3 + 1/4 + 1/582series_sum→ 137/60 = sum(Fraction(1, i) for i in range(1, 6))83print(f"1/1 + 1/2 + 1/3 + 1/4 + 1/5 = {series_sum137/60}")84print(f" = {float(series_sum137/60):.6f}")8586# Harmonic series87print("\nHarmonic series (first 10 terms):")88harmonic→ 7381/2520 = sum(Fraction(1, i) for i in range(1, 11))89print(f"H_10 = {harmonic7381/2520}")90print(f" ≈ {float(harmonic7381/2520):.10f}")9192# Factorial fractions93print("\nFactorial fractions:")94# 1/1! + 1/2! + 1/3! + 1/4!95import math96factorial_sum→ 41/24 = sum(Fraction(1, math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(i)) for i in range(1, 5))97print(f"1/1! + 1/2! + 1/3! + 1/4! = {factorial_sum41/24}")98print(f" = {float(factorial_sum41/24):.10f}")99print(f" (approaching e-1 = {math.e2.718281828459045 - 1:.10f})")100101# Dividing whole cake102print("\nDividing cake:")103cake→ 1 = Fraction(1) # Whole cake104people→ 8 = 8 #@people=4, 12105slice_size→ 1/8 = cake1 / people8106print(f"Cake for {people8} people: {slice_size1/8} each")107print(f"3 people get: {slice_size1/8 * 3}")108109# Recipe scaling110print("\nRecipe scaling:")111original→ 2/3 = Fraction(2, 3) # 2/3 cup112scale_factor→ 3/2 = Fraction(3, 2) # 1.5x recipe113scaled→ 1 = original2/3 * scale_factor3/2114print(f"Original: {original2/3} cup")115print(f"Scaled by {scale_factor3/2}: {scaled1} cup")116print(f" = {float(scaled1)} cup")outputa = 3/4 b = 2/5 Addition: a + b = 23/20 = 23/20 Subtraction: a - b = 7/20 Multiplication: a * b = 3/10 = 6/20 Division: a / b = 15/8 = 15/8 Floor division: a // b = 1 Modulo: a % b = 7/20 Power: 2/3^2 = 4/9 2/3^3 = 8/27 2/3^-1 = 3/2 Negation: -a = -3/4 Absolute value: abs(-3/4) = 3/4 Reciprocal: Reciprocal of 3/4 = 4/3 = 4/3 Mixed operations: Fraction + int: 11/4 int + Fraction: 11/4 Fraction * int: 9/4 Fraction / int: 3/8 Chaining: 1/2 + 1/3 + 1/6 = 1 Complex expression: (3/4 * 2/5 + 1/2) / 3/8 = 32/15 Sum of series: 1/1 + 1/2 + 1/3 + 1/4 + 1/5 = 137/60 = 2.283333 Harmonic series (first 10 terms): H_10 = 7381/2520 ≈ 2.9289682540 Factorial fractions: 1/1! + 1/2! + 1/3! + 1/4! = 41/24 = 1.7083333333 (approaching e-1 = 1.7182818285) Dividing cake: Cake for 8 people: 1/8 each 3 people get: 3/8 Recipe scaling: Original: 2/3 cup Scaled by 3/2: 1 cup = 1.0 cup
a ← 3/4, b ← 2/5, f ← 2/3, neg ← -3/4, result ← 1, expr ← 32/15
5# Arithmetic6a→ 3/4 = Fraction(3, 4)7b→ 2/5 = Fraction(2, 5)89print(f"a = {a3/4}")10print(f"b = {b2/5}")11print()1213# Addition14print("Addition:")15print(f"a + b = {a3/4 + b2/5}")16print(f" = {a.numerator3 * b.denominator5 + b.numerator2 * a.denominator4}/{a.denominator * b.denominator}")1718# Subtraction19print("\nSubtraction:")20print(f"a - b = {a3/4 - b2/5}")2122# Multiplication23print("\nMultiplication:")24print(f"a * b = {a3/4 * b2/5}")25print(f" = {a.numerator3 * b.numerator2}/{a.denominator4 * b.denominator5}")2627# Division28print("\nDivision:")29print(f"a / b = {a3/4 / b2/5}")30print(f" = {a.numerator3 * b.denominator5}/{a.denominator4 * b.numerator2}")3132# Floor division33print("\nFloor division:")34print(f"a // b = {a3/4 // b2/5}")3536# Modulo37print("\nModulo:")38print(f"a % b = {a3/4 % b2/5}")3940# Power41print("\nPower:")42f→ 2/3 = Fraction(2, 3)43print(f"{f2/3}^2 = {f ** 2}")44print(f"{f2/3}^3 = {f ** 3}")45print(f"{f2/3}^-1 = {f ** -1}") # Reciprocal4647# Negation48print("\nNegation:")49print(f"-a = {-a3/4}")5051# Absolute value52print("\nAbsolute value:")53neg→ -3/4 = Fraction(-3, 4)54print(f"abs({neg-3/4}) = {abs(neg)}")5556# Reciprocal57print("\nReciprocal:")58f→ 3/4 = Fraction(3, 4)59print(f"Reciprocal of {f3/4} = {1 / f}")60print(f" = {Fraction(f.denominator4, f.numerator3)}")6162# Mixed operations63print("\nMixed operations:")64print(f"Fraction + int: {a3/4 + 2}")65print(f"int + Fraction: {2 + a3/4}")66print(f"Fraction * int: {a3/4 * 3}")67print(f"Fraction / int: {a3/4 / 2}")6869# Chaining70print("\nChaining:")71result→ 1 = Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6)72print(f"1/2 + 1/3 + 1/6 = {result1}")7374# Complex expression75print("\nComplex expression:")76expr→ 32/15 = (Fraction(3, 4) * Fraction(2, 5) + Fraction(1, 2)) / Fraction(3, 8)77print(f"(3/4 * 2/5 + 1/2) / 3/8 = {expr32/15}")7879# Sum of series80print("\nSum of series:")81# 1/1 + 1/2 + 1/3 + 1/4 + 1/582series_sum→ 137/60 = sum(Fraction(1, i) for i in range(1, 6))83print(f"1/1 + 1/2 + 1/3 + 1/4 + 1/5 = {series_sum137/60}")84print(f" = {float(series_sum137/60):.6f}")8586# Harmonic series87print("\nHarmonic series (first 10 terms):")88harmonic→ 7381/2520 = sum(Fraction(1, i) for i in range(1, 11))89print(f"H_10 = {harmonic7381/2520}")90print(f" ≈ {float(harmonic7381/2520):.10f}")9192# Factorial fractions93print("\nFactorial fractions:")94# 1/1! + 1/2! + 1/3! + 1/4!95import math96factorial_sum→ 41/24 = sum(Fraction(1, math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(i)) for i in range(1, 5))97print(f"1/1! + 1/2! + 1/3! + 1/4! = {factorial_sum41/24}")98print(f" = {float(factorial_sum41/24):.10f}")99print(f" (approaching e-1 = {math.e2.718281828459045 - 1:.10f})")100101# Dividing whole cake102print("\nDividing cake:")103cake→ 1 = Fraction(1) # Whole cake104people→ 4 = 4105slice_size→ 1/4 = cake1 / people4106print(f"Cake for {people4} people: {slice_size1/4} each")107print(f"3 people get: {slice_size1/4 * 3}")108109# Recipe scaling110print("\nRecipe scaling:")111original→ 2/3 = Fraction(2, 3) # 2/3 cup112scale_factor→ 3/2 = Fraction(3, 2) # 1.5x recipe113scaled→ 1 = original2/3 * scale_factor3/2114print(f"Original: {original2/3} cup")115print(f"Scaled by {scale_factor3/2}: {scaled1} cup")116print(f" = {float(scaled1)} cup")outputa = 3/4 b = 2/5 Addition: a + b = 23/20 = 23/20 Subtraction: a - b = 7/20 Multiplication: a * b = 3/10 = 6/20 Division: a / b = 15/8 = 15/8 Floor division: a // b = 1 Modulo: a % b = 7/20 Power: 2/3^2 = 4/9 2/3^3 = 8/27 2/3^-1 = 3/2 Negation: -a = -3/4 Absolute value: abs(-3/4) = 3/4 Reciprocal: Reciprocal of 3/4 = 4/3 = 4/3 Mixed operations: Fraction + int: 11/4 int + Fraction: 11/4 Fraction * int: 9/4 Fraction / int: 3/8 Chaining: 1/2 + 1/3 + 1/6 = 1 Complex expression: (3/4 * 2/5 + 1/2) / 3/8 = 32/15 Sum of series: 1/1 + 1/2 + 1/3 + 1/4 + 1/5 = 137/60 = 2.283333 Harmonic series (first 10 terms): H_10 = 7381/2520 ≈ 2.9289682540 Factorial fractions: 1/1! + 1/2! + 1/3! + 1/4! = 41/24 = 1.7083333333 (approaching e-1 = 1.7182818285) Dividing cake: Cake for 4 people: 1/4 each 3 people get: 3/4 Recipe scaling: Original: 2/3 cup Scaled by 3/2: 1 cup = 1.0 cup
a ← 3/4, b ← 2/5, f ← 2/3, neg ← -3/4, result ← 1, expr ← 32/15
5# Arithmetic6a→ 3/4 = Fraction(3, 4)7b→ 2/5 = Fraction(2, 5)89print(f"a = {a3/4}")10print(f"b = {b2/5}")11print()1213# Addition14print("Addition:")15print(f"a + b = {a3/4 + b2/5}")16print(f" = {a.numerator3 * b.denominator5 + b.numerator2 * a.denominator4}/{a.denominator * b.denominator}")1718# Subtraction19print("\nSubtraction:")20print(f"a - b = {a3/4 - b2/5}")2122# Multiplication23print("\nMultiplication:")24print(f"a * b = {a3/4 * b2/5}")25print(f" = {a.numerator3 * b.numerator2}/{a.denominator4 * b.denominator5}")2627# Division28print("\nDivision:")29print(f"a / b = {a3/4 / b2/5}")30print(f" = {a.numerator3 * b.denominator5}/{a.denominator4 * b.numerator2}")3132# Floor division33print("\nFloor division:")34print(f"a // b = {a3/4 // b2/5}")3536# Modulo37print("\nModulo:")38print(f"a % b = {a3/4 % b2/5}")3940# Power41print("\nPower:")42f→ 2/3 = Fraction(2, 3)43print(f"{f2/3}^2 = {f ** 2}")44print(f"{f2/3}^3 = {f ** 3}")45print(f"{f2/3}^-1 = {f ** -1}") # Reciprocal4647# Negation48print("\nNegation:")49print(f"-a = {-a3/4}")5051# Absolute value52print("\nAbsolute value:")53neg→ -3/4 = Fraction(-3, 4)54print(f"abs({neg-3/4}) = {abs(neg)}")5556# Reciprocal57print("\nReciprocal:")58f→ 3/4 = Fraction(3, 4)59print(f"Reciprocal of {f3/4} = {1 / f}")60print(f" = {Fraction(f.denominator4, f.numerator3)}")6162# Mixed operations63print("\nMixed operations:")64print(f"Fraction + int: {a3/4 + 2}")65print(f"int + Fraction: {2 + a3/4}")66print(f"Fraction * int: {a3/4 * 3}")67print(f"Fraction / int: {a3/4 / 2}")6869# Chaining70print("\nChaining:")71result→ 1 = Fraction(1, 2) + Fraction(1, 3) + Fraction(1, 6)72print(f"1/2 + 1/3 + 1/6 = {result1}")7374# Complex expression75print("\nComplex expression:")76expr→ 32/15 = (Fraction(3, 4) * Fraction(2, 5) + Fraction(1, 2)) / Fraction(3, 8)77print(f"(3/4 * 2/5 + 1/2) / 3/8 = {expr32/15}")7879# Sum of series80print("\nSum of series:")81# 1/1 + 1/2 + 1/3 + 1/4 + 1/582series_sum→ 137/60 = sum(Fraction(1, i) for i in range(1, 6))83print(f"1/1 + 1/2 + 1/3 + 1/4 + 1/5 = {series_sum137/60}")84print(f" = {float(series_sum137/60):.6f}")8586# Harmonic series87print("\nHarmonic series (first 10 terms):")88harmonic→ 7381/2520 = sum(Fraction(1, i) for i in range(1, 11))89print(f"H_10 = {harmonic7381/2520}")90print(f" ≈ {float(harmonic7381/2520):.10f}")9192# Factorial fractions93print("\nFactorial fractions:")94# 1/1! + 1/2! + 1/3! + 1/4!95import math96factorial_sum→ 41/24 = sum(Fraction(1, math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.factorial(i)) for i in range(1, 5))97print(f"1/1! + 1/2! + 1/3! + 1/4! = {factorial_sum41/24}")98print(f" = {float(factorial_sum41/24):.10f}")99print(f" (approaching e-1 = {math.e2.718281828459045 - 1:.10f})")100101# Dividing whole cake102print("\nDividing cake:")103cake→ 1 = Fraction(1) # Whole cake104people→ 12 = 12105slice_size→ 1/12 = cake1 / people12106print(f"Cake for {people12} people: {slice_size1/12} each")107print(f"3 people get: {slice_size1/12 * 3}")108109# Recipe scaling110print("\nRecipe scaling:")111original→ 2/3 = Fraction(2, 3) # 2/3 cup112scale_factor→ 3/2 = Fraction(3, 2) # 1.5x recipe113scaled→ 1 = original2/3 * scale_factor3/2114print(f"Original: {original2/3} cup")115print(f"Scaled by {scale_factor3/2}: {scaled1} cup")116print(f" = {float(scaled1)} cup")outputa = 3/4 b = 2/5 Addition: a + b = 23/20 = 23/20 Subtraction: a - b = 7/20 Multiplication: a * b = 3/10 = 6/20 Division: a / b = 15/8 = 15/8 Floor division: a // b = 1 Modulo: a % b = 7/20 Power: 2/3^2 = 4/9 2/3^3 = 8/27 2/3^-1 = 3/2 Negation: -a = -3/4 Absolute value: abs(-3/4) = 3/4 Reciprocal: Reciprocal of 3/4 = 4/3 = 4/3 Mixed operations: Fraction + int: 11/4 int + Fraction: 11/4 Fraction * int: 9/4 Fraction / int: 3/8 Chaining: 1/2 + 1/3 + 1/6 = 1 Complex expression: (3/4 * 2/5 + 1/2) / 3/8 = 32/15 Sum of series: 1/1 + 1/2 + 1/3 + 1/4 + 1/5 = 137/60 = 2.283333 Harmonic series (first 10 terms): H_10 = 7381/2520 ≈ 2.9289682540 Factorial fractions: 1/1! + 1/2! + 1/3! + 1/4! = 41/24 = 1.7083333333 (approaching e-1 = 1.7182818285) Dividing cake: Cake for 12 people: 1/12 each 3 people get: 1/4 Recipe scaling: Original: 2/3 cup Scaled by 3/2: 1 cup = 1.0 cup
Conversions
Converting between fractions and other types:
convert.py
Replay: real traced execution (multi-file project)
# Converting and formatting
from fractions import Fraction
from decimal import Decimal
import math
# Convert to other types
print("Convert to other types:")
f = Fraction(3, 4)
print(f"Fraction: {f}")
print(f"float: {float(f)}")
print(f"int (truncate): {int(f)}")
print(f"str: {str(f)}")
print()
# To Decimal
print("To Decimal:")
dec = Decimal(f.numerator) / Decimal(f.denominator)
print(f"{f} as Decimal: {dec}")
# Different fractions
print("\nDifferent fractions to float:")
fractions = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(2, 3)]
for frac in fractions:
print(f"{frac} = {float(frac):.10f}")
# Formatting
print("\nFormatting:")
f = Fraction(22, 7) # Approximation of pi
print(f"Default: {f}")
print(f"Float: {float(f):.6f}")
print(f"Percentage: {float(f) * 100:.2f}%")
# Mixed number representation
print("\nMixed number representation:")
def to_mixed_number(frac):
"""Convert improper fraction to mixed number."""
whole = frac.numerator // frac.denominator
remainder = frac.numerator % frac.denominator
if remainder == 0:
return f"{whole}"
elif whole == 0:
return f"{remainder}/{frac.denominator}"
else:
return f"{whole} {remainder}/{frac.denominator}"
improper_fracs = [Fraction(7, 4), Fraction(11, 3), Fraction(5, 2), Fraction(8, 4)]
for f in improper_fracs:
print(f"{f} = {to_mixed_number(f)}")
# Decimal to Fraction
print("\nDecimal to Fraction:")
decimals = [0.5, 0.25, 0.75, 0.125, 0.333]
for d in decimals:
f = Fraction(d).limit_denominator(1000)
print(f"{d} ≈ {f}")
# String to Fraction
print("\nString to Fraction:")
strings = ['1/2', '3/4', '0.5', '0.75', '22/7']
for s in strings:
f = Fraction(s)
print(f"'{s}' = {f} = {float(f):.6f}")
# Pi approximations
print("\nPi approximations:")
pi_approx = [
Fraction(22, 7),
Fraction(355, 113),
Fraction(103993, 33102),
]
for f in pi_approx:
error = abs(float(f) - math.pi)
print(f"{f} = {float(f):.10f} (error: {error:.2e})")
print(f"Actual π = {math.pi:.10f}")
# Common percentages as fractions
print("\nCommon percentages:")
percentages = [10, 20, 25, 33.33, 50, 75, 100]
for pct in percentages:
f = Fraction(str(pct / 100)).limit_denominator(100)
print(f"{pct}% = {f} = {float(f):.4f}")
# Continued fractions (representation)
print("\nContinued fraction representation:")
def continued_fraction(frac, max_terms=10):
"""Get continued fraction representation."""
terms = []
n, d = frac.numerator, frac.denominator
for _ in range(max_terms):
if d == 0:
break
q, r = divmod(n, d)
terms.append(q)
n, d = d, r
if r == 0:
break
return terms
f = Fraction(22, 7)
cf = continued_fraction(f)
print(f"{f}: {cf}")
f = Fraction(355, 113)
cf = continued_fraction(f)
print(f"{f}: {cf}")
# Reconstruct from numerator/denominator
print("\nReconstruct fraction:")
num, den = 3, 4
reconstructed = Fraction(num, den)
print(f"From {num}/{den}: {reconstructed}")
# Using with f-strings
print("\nF-string formatting:")
f = Fraction(3, 4)
print(f"Fraction: {f}")
print(f"As float: {float(f):.2f}")
print(f"As percentage: {float(f):.1%}")
f ← 3/4, dec ← 0.75, fractions ← [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(2, 3)]
7# Convert to other types8print("Convert to other types:")9f→ 3/4 = Fraction(3, 4)1011print(f"Fraction: {f3/4}")12print(f"float: {float(f3/4)}")13print(f"int (truncate): {int(f3/4)}")14print(f"str: {str(f3/4)}")15print()1617# To Decimal18print("To Decimal:")19dec→ 0.75 = Decimal(f.numerator3) / Decimal(f.denominator4)20print(f"{f3/4} as Decimal: {dec0.75}")2122# Different fractions23print("\nDifferent fractions to float:")24fractions→ [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(2, 3)] = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(2, 3)]25for frac in fractions:outputConvert to other types: Fraction: 3/4 float: 0.75 int (truncate): 0 str: 3/4 To Decimal: 3/4 as Decimal: 0.75 Different fractions to float:for frac in fractions:
pass 1 of 424fractions = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(2, 3)]25for frac1/2 in fractions[Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(2, 3)]:26 print(f"{frac1/2} = {float(frac):.10f}")output1/2 = 0.5000000000All 4 passes — pass 1 is the card above pass frac1 1/2 2 1/3 3 1/4 4 2/3 f ← 22/7, improper_fracs ← [Fraction(7, 4), Fraction(11, 3), Fraction(5, 2), Fraction(2, 1)]
28# Formatting29print("\nFormatting:")30f→ 22/7 = Fraction(22, 7) # Approximation of pi31print(f"Default: {f22/7}")32print(f"Float: {float(f22/7):.6f}")33print(f"Percentage: {float(f22/7) * 100:.2f}%")3435# Mixed number representation36print("\nMixed number representation:")37def to_mixed_number(frac):38 """Convert improper fraction to mixed number."""39 whole = frac.numerator // frac.denominator40 remainder = frac.numerator % frac.denominator41 if remainder == 0:42 return f"{whole}"43 elif whole == 0:44 return f"{remainder}/{frac.denominator}"45 else:46 return f"{whole} {remainder}/{frac.denominator}"4748improper_fracs→ [Fraction(7, 4), Fraction(11, 3), Fraction(5, 2), Fraction(2, 1)] = [Fraction(7, 4), Fraction(11, 3), Fraction(5, 2), Fraction(8, 4)]49for f in improper_fracs:output Formatting: Default: 22/7 Float: 3.142857 Percentage: 314.29% Mixed number representation:for f in improper_fracs:
pass 1 of 448improper_fracs = [Fraction(7, 4), Fraction(11, 3), Fraction(5, 2), Fraction(8, 4)]49for f7/4 in improper_fracs[Fraction(7, 4), Fraction(11, 3), Fraction(5, 2), Fraction(2, 1)]:50 print(f"{f7/4} = {to_mixed_number(f)}")All 4 passes — pass 1 is the card above pass fremainderwhole1 7/4 — — 2 11/3 — — 3 5/2 — — 4 2 0 2 whole ← 1, remainder ← 3
pass 1 of 436print("\nMixed number representation:")37def to_mixed_number(frac7/4):38 """Convert improper fraction to mixed number."""39 whole→ 1 = frac.numerator7 // frac.denominator440 remainder→ 3 = frac.numerator7 % frac.denominator441 if remainder == 0:All 4 passes — pass 1 is the card above pass fracfrac.numeratorfrac.denominatorwholeremainder1 7/4 7 4 1 3 2 11/3 11 3 3 2 3 5/2 5 2 2 1 4 2 2 1 2 0 else:
pass 1 of 343elif whole == 0:44 return f"{remainder}/{frac.denominator}"45else:46 return f"{whole1} {remainder3}/{frac.denominator4}"All 3 passes — pass 1 is the card above pass wholeremainderfrac.denominator1 1 3 4 2 3 2 3 3 2 1 2 print(f"{f} = {to_mixed_number(f)}")
49for f in improper_fracs:50 print(f"{f7/4} = {to_mixed_number(f)}")output7/4 = 1 3/4print(f"{f} = {to_mixed_number(f)}")
49for f in improper_fracs:50 print(f"{f11/3} = {to_mixed_number(f)}")output11/3 = 3 2/3print(f"{f} = {to_mixed_number(f)}")
49for f in improper_fracs:50 print(f"{f5/2} = {to_mixed_number(f)}")output5/2 = 2 1/2if remainder == 0:
40remainder = frac.numerator % frac.denominator41if remainder0 == 0:42 return f"{whole2}"43elif whole == 0:print(f"{f} = {to_mixed_number(f)}")
49for f in improper_fracs:50 print(f"{f2} = {to_mixed_number(f)}")output2 = 2decimals ← [0.5, 0.25, 0.75, 0.125, 0.333]
52# Decimal to Fraction53print("\nDecimal to Fraction:")54decimals→ [0.5, 0.25, 0.75, 0.125, 0.333] = [0.5, 0.25, 0.75, 0.125, 0.333]55for d in decimals:output Decimal to Fraction:f ← 1/2
pass 1 of 554decimals = [0.5, 0.25, 0.75, 0.125, 0.333]55for d0.5 in decimals[0.5, 0.25, 0.75, 0.125, 0.333]:56 f→ 1/2 = Fraction(d0.5).limit_denominator(1000)57 print(f"{d0.5} ≈ {f1/2}")output0.5 ≈ 1/2All 5 passes — pass 1 is the card above pass df1 0.5 1/2 2 0.25 1/4 3 0.75 3/4 4 0.125 1/8 5 0.333 333/1000 strings ← ['1/2', '3/4', '0.5', '0.75', '22/7']
59# String to Fraction60print("\nString to Fraction:")61strings→ ['1/2', '3/4', '0.5', '0.75', '22/7'] = ['1/2', '3/4', '0.5', '0.75', '22/7']62for s in strings:output String to Fraction:f ← 1/2
pass 1 of 561strings = ['1/2', '3/4', '0.5', '0.75', '22/7']62for s1/2 in strings['1/2', '3/4', '0.5', '0.75', '22/7']:63 f→ 1/2 = Fraction(s1/2)64 print(f"'{s1/2}' = {f1/2} = {float(f):.6f}")output'1/2' = 1/2 = 0.500000All 5 passes — pass 1 is the card above pass sf1 1/2 1/2 2 3/4 3/4 3 0.5 1/2 4 0.75 3/4 5 22/7 22/7 pi_approx ← [Fraction(22, 7), Fraction(355, 113), Fraction(103993, 33102)]
66# Pi approximations67print("\nPi approximations:")68pi_approx→ [Fraction(22, 7), Fraction(355, 113), Fraction(103993, 33102)] = [69 Fraction(22, 7),70 Fraction(355, 113),71 Fraction(103993, 33102),72]73for f in pi_approx:output Pi approximations:error ← 0.0012644892673496777
pass 1 of 372]73for f22/7 in pi_approx[Fraction(22, 7), Fraction(355, 113), Fraction(103993, 33102)]:74 error→ 0.0012644892673496777 = abs(float(f22/7) - math.pi3.141592653589793)75 print(f"{f22/7} = {float(f):.10f} (error: {error0.0012644892673496777:.2e})")76print(f"Actual π = {math.pi:.10f}")output22/7 = 3.1428571429 (error: 1.26e-03)All 3 passes — pass 1 is the card above pass ferror1 22/7 0.0012644892673496777 2 355/113 2.667641894049666e-07 3 103993/33102 5.778906242426274e-10 percentages ← [10, 20, 25, 33.33, 50, 75, 100]
75 print(f"{f} = {float(f):.10f} (error: {error:.2e})")76print(f"Actual π = {math.pi3.141592653589793:.10f}")7778# Common percentages as fractions79print("\nCommon percentages:")80percentages→ [10, 20, 25, 33.33, 50, 75, 100] = [10, 20, 25, 33.33, 50, 75, 100]81for pct in percentages:outputActual π = 3.1415926536 Common percentages:f ← 1/10
pass 1 of 780percentages = [10, 20, 25, 33.33, 50, 75, 100]81for pct10 in percentages[10, 20, 25, 33.33, 50, 75, 100]:82 f→ 1/10 = Fraction(str(pct10 / 100)).limit_denominator(100)83 print(f"{pct10}% = {f1/10} = {float(f):.4f}")output10% = 1/10 = 0.1000All 7 passes — pass 1 is the card above pass pctf1 10 1/10 2 20 1/5 3 25 1/4 4 33.33 1/3 5 50 1/2 6 75 3/4 7 100 1 f ← 22/7
85# Continued fractions (representation)86print("\nContinued fraction representation:")87def continued_fraction(frac, max_terms=10):88 """Get continued fraction representation."""89 terms = []90 n, d = frac.numerator, frac.denominator91 for _ in range(max_terms):92 if d == 0:93 break94 q, r = divmod(n, d)95 terms.append(q)96 n, d = d, r97 if r == 0:98 break99 return terms100101f→ 22/7 = Fraction(22, 7)102cf = continued_fraction(f22/7)103print(f"{f}: {cf}")output Continued fraction representation:terms ← [], n ← 22, d ← 7
pass 1 of 286print("\nContinued fraction representation:")87def continued_fraction(frac22/7, max_terms10=10):88 """Get continued fraction representation."""89 terms→ [] = []90 n→ 22, d→ 7 = frac.numerator22, frac.denominator791 for _ in range(max_terms):q ← 3, r ← 1, terms ← [3], n ← 7, d ← 1
pass 1 of 590n, d = frac.numerator, frac.denominator91for _0 in range(max_terms10):92 if d == 0:93 break94 q→ 3, r→ 1 = divmod(n22, d7)95 terms→ [3].append(q3)96 n→ 7, d→ 1 = d, r197 if r == 0:All 5 passes — pass 1 is the card above pass _qrtermsnd1 0 3 1 [] → [3] 22 → 7 7 → 1 2 1 7 0 [3] → [3, 7] 7 → 1 1 → 0 3 0 3 16 [] → [3] 355 → 113 113 → 16 4 1 7 1 [3] → [3, 7] 113 → 16 16 → 1 5 2 16 0 [3, 7] → [3, 7, 16] 16 → 1 1 → 0 if r == 0:
pass 1 of 296 n, d = d, r97 if r0 == 0:98 break99return termsreturn terms
98 break99return terms[3, 7]cf ← [3, 7], f ← 355/113
101f = Fraction(22, 7)102cf→ [3, 7] = continued_fraction(f22/7)103print(f"{f22/7}: {cf[3, 7]}")104105f→ 355/113 = Fraction(355, 113)106cf = continued_fraction(f355/113)107print(f"{f}: {cf}")output22/7: [3, 7]terms ← [], n ← 355, d ← 113
pass 2 of 286print("\nContinued fraction representation:")87def continued_fraction(frac355/113, max_terms10=10):88 """Get continued fraction representation."""89 terms→ [] = []90 n→ 355, d→ 113 = frac.numerator355, frac.denominator11391 for _ in range(max_terms):if r == 0:
pass 2 of 296 n, d = d, r97 if r0 == 0:98 break99return termsreturn terms
98 break99return terms[3, 7, 16]cf ← [3, 7, 16], num ← 3, den ← 4, reconstructed ← 3/4, f ← 3/4
105f = Fraction(355, 113)106cf→ [3, 7, 16] = continued_fraction(f355/113)107print(f"{f355/113}: {cf[3, 7, 16]}")108109# Reconstruct from numerator/denominator110print("\nReconstruct fraction:")111num→ 3, den→ 4 = 3, 4112reconstructed→ 3/4 = Fraction(num3, den4)113print(f"From {num3}/{den4}: {reconstructed3/4}")114115# Using with f-strings116print("\nF-string formatting:")117f→ 3/4 = Fraction(3, 4)118print(f"Fraction: {f3/4}")119print(f"As float: {float(f3/4):.2f}")120print(f"As percentage: {float(f3/4):.1%}")output355/113: [3, 7, 16] Reconstruct fraction: From 3/4: 3/4 F-string formatting: Fraction: 3/4 As float: 0.75 As percentage: 75.0%
limit_denominator()
Finds the closest fraction with a denominator at or below a specified limit - useful for approximating floats as simple fractions.
Comparisons
Comparing fractions:
comparison.py
Replay: real traced execution (multi-file project)
# Comparison operations
from fractions import Fraction
# Comparison
a = Fraction(3, 4)
b = Fraction(2, 3)
c = Fraction(6, 8) # Same as 3/4
print(f"a = {a}")
print(f"b = {b}")
print(f"c = {c}")
print()
# Equality
print("Equality:")
print(f"a == b: {a == b}")
print(f"a == c: {a == c}")
print(f"a != b: {a != b}")
# Ordering
print("\nOrdering:")
print(f"a < b: {a < b}")
print(f"a <= b: {a <= b}")
print(f"a > b: {a > b}")
print(f"a >= b: {a >= b}")
# Compare with numbers
print("\nCompare with numbers:")
f = Fraction(1, 2)
print(f"{f} == 0.5: {f == 0.5}")
print(f"{f} > 0.4: {f > 0.4}")
print(f"{f} < 1: {f < 1}")
# max and min
print("\nmax and min:")
fractions = [Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)]
print(f"Fractions: {fractions}")
print(f"Max: {max(fractions)}")
print(f"Min: {min(fractions)}")
# Sort
print("\nSort:")
unsorted = [Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)]
sorted_fracs = sorted(unsorted)
print(f"Unsorted: {unsorted}")
print(f"Sorted: {sorted_fracs}")
# Sort descending
print("\nSort descending:")
desc = sorted(unsorted, reverse=True)
print(f"Descending: {desc}")
# Find max in different forms
print("\nCompare different representations:")
vals = [Fraction(3, 4), 0.75, Fraction('0.75')]
print(f"Values: {vals}")
print(f"All equal: {vals[0] == vals[1] == vals[2]}")
# Range check
print("\nRange check:")
value = Fraction(1, 2)
lower = Fraction(1, 4)
upper = Fraction(3, 4)
in_range = lower <= value <= upper
print(f"{value} in [{lower}, {upper}]: {in_range}")
# Zero comparison
print("\nZero comparison:")
zero = Fraction(0)
pos = Fraction(1, 2)
neg = Fraction(-1, 2)
print(f"{zero} == 0: {zero == 0}")
print(f"{pos} > 0: {pos > 0}")
print(f"{neg} < 0: {neg < 0}")
# Proper vs improper fractions
print("\nProper vs improper fractions:")
proper = Fraction(3, 4) # < 1
improper = Fraction(5, 4) # > 1
print(f"{proper} is proper (< 1): {proper < 1}")
print(f"{improper} is improper (> 1): {improper > 1}")
# Compare fractions visually
print("\nCompare fractions:")
fracs = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5)]
for f in fracs:
bar = '█' * int(f * 20)
print(f"{str(f):>4} = {float(f):.4f} {bar}")
# Unit fractions (1/n)
print("\nUnit fractions (sorted):")
units = [Fraction(1, i) for i in range(2, 11)]
for f in units:
print(f"1/{f.denominator} = {float(f):.6f}")
# Egyptian fractions comparison
print("\nEgyptian fractions (distinct unit fractions):")
# 5/6 = 1/2 + 1/3
frac = Fraction(5, 6)
decomp = Fraction(1, 2) + Fraction(1, 3)
print(f"{frac} == 1/2 + 1/3: {frac == decomp}")
# Tolerance comparison (not usually needed)
print("\nTolerance comparison (for demonstration):")
f1 = Fraction(1, 3)
f2 = Fraction(333, 1000) # Approximate 1/3
diff = abs(f1 - f2)
tolerance = Fraction(1, 100)
approx_equal = diff <= tolerance
print(f"{f1} ≈ {f2} (tolerance {tolerance}): {approx_equal}")
print(f"Difference: {diff}")
a ← 3/4, b ← 2/3, c ← 3/4, f ← 1/2, fractions ← [Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)]
5# Comparison6a→ 3/4 = Fraction(3, 4)7b→ 2/3 = Fraction(2, 3)8c→ 3/4 = Fraction(6, 8) # Same as 3/4910print(f"a = {a3/4}")11print(f"b = {b2/3}")12print(f"c = {c3/4}")13print()1415# Equality16print("Equality:")17print(f"a == b: {a3/4 == b2/3}")18print(f"a == c: {a3/4 == c3/4}")19print(f"a != b: {a3/4 != b2/3}")2021# Ordering22print("\nOrdering:")23print(f"a < b: {a3/4 < b2/3}")24print(f"a <= b: {a3/4 <= b2/3}")25print(f"a > b: {a3/4 > b2/3}")26print(f"a >= b: {a3/4 >= b2/3}")2728# Compare with numbers29print("\nCompare with numbers:")30f→ 1/2 = Fraction(1, 2)31print(f"{f1/2} == 0.5: {f == 0.5}")32print(f"{f1/2} > 0.4: {f > 0.4}")33print(f"{f1/2} < 1: {f < 1}")3435# max and min36print("\nmax and min:")37fractions→ [Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)] = [Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)]38print(f"Fractions: {fractions[Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)]}")39print(f"Max: {max(fractions[Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)])}")40print(f"Min: {min(fractions[Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)])}")4142# Sort43print("\nSort:")44unsorted→ [Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)] = [Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)]45sorted_fracs→ [Fraction(1, 4), Fraction(1, 2), Fraction(2, 3), Fraction(3, 4)] = sorted(unsorted[Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)])46print(f"Unsorted: {unsorted[Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)]}")47print(f"Sorted: {sorted_fracs[Fraction(1, 4), Fraction(1, 2), Fraction(2, 3), Fraction(3, 4)]}")4849# Sort descending50print("\nSort descending:")51desc→ [Fraction(3, 4), Fraction(2, 3), Fraction(1, 2), Fraction(1, 4)] = sorted(unsorted[Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)], reverse=True)52print(f"Descending: {desc[Fraction(3, 4), Fraction(2, 3), Fraction(1, 2), Fraction(1, 4)]}")5354# Find max in different forms55print("\nCompare different representations:")56vals→ [Fraction(3, 4), 0.75, Fraction(3, 4)] = [Fraction(3, 4), 0.75, Fraction('0.75')]57print(f"Values: {vals[Fraction(3, 4), 0.75, Fraction(3, 4)]}")58print(f"All equal: {vals[0]3/4 == vals[1]0.75 == vals[2]3/4}")5960# Range check61print("\nRange check:")62value→ 1/2 = Fraction(1, 2)63lower→ 1/4 = Fraction(1, 4)64upper→ 3/4 = Fraction(3, 4)65in_range→ True = lower1/4 <= value1/2 <= upper3/466print(f"{value1/2} in [{lower1/4}, {upper3/4}]: {in_rangeTrue}")6768# Zero comparison69print("\nZero comparison:")70zero→ 0 = Fraction(0)71pos→ 1/2 = Fraction(1, 2)72neg→ -1/2 = Fraction(-1, 2)7374print(f"{zero0} == 0: {zero == 0}")75print(f"{pos1/2} > 0: {pos > 0}")76print(f"{neg-1/2} < 0: {neg < 0}")7778# Proper vs improper fractions79print("\nProper vs improper fractions:")80proper→ 3/4 = Fraction(3, 4) # < 181improper→ 5/4 = Fraction(5, 4) # > 18283print(f"{proper3/4} is proper (< 1): {proper < 1}")84print(f"{improper5/4} is improper (> 1): {improper > 1}")8586# Compare fractions visually87print("\nCompare fractions:")88fracs→ [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5)] = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5)]89for f in fracs:outputa = 3/4 b = 2/3 c = 3/4 Equality: a == b: False a == c: True a != b: True Ordering: a < b: False a <= b: False a > b: True a >= b: True Compare with numbers: 1/2 == 0.5: True 1/2 > 0.4: True 1/2 < 1: True max and min: Fractions: [Fraction(1, 2), Fraction(1, 3), Fraction(2, 3), Fraction(1, 4)] Max: 2/3 Min: 1/4 Sort: Unsorted: [Fraction(2, 3), Fraction(1, 4), Fraction(3, 4), Fraction(1, 2)] Sorted: [Fraction(1, 4), Fraction(1, 2), Fraction(2, 3), Fraction(3, 4)] Sort descending: Descending: [Fraction(3, 4), Fraction(2, 3), Fraction(1, 2), Fraction(1, 4)] Compare different representations: Values: [Fraction(3, 4), 0.75, Fraction(3, 4)] All equal: True Range check: 1/2 in [1/4, 3/4]: True Zero comparison: 0 == 0: True 1/2 > 0: True -1/2 < 0: True Proper vs improper fractions: 3/4 is proper (< 1): True 5/4 is improper (> 1): True Compare fractions:bar ← ██████████
pass 1 of 488fracs = [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5)]89for f1/2 in fracs[Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5)]:90 bar→ ██████████ = '█' * int(f1/2 * 20)91 print(f"{str(f1/2):>4} = {float(f):.4f} {bar██████████}")output 1/2 = 0.5000 ██████████All 4 passes — pass 1 is the card above pass fbar1 1/2 ██████████ 2 1/3 ██████ 3 1/4 █████ 4 1/5 ████ units ← [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5), Fraction(1, 6), Fraction(1, 7), Fraction(1, 8), Fraction(1, 9), Fraction(1, 10)]
93# Unit fractions (1/n)94print("\nUnit fractions (sorted):")95units→ [Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5), Fraction(1, 6), Fraction(1, 7), Fraction(1, 8), Fraction(1, 9), Fraction(1, 10)] = [Fraction(1, i) for i in range(2, 11)]96for f in units:output Unit fractions (sorted):for f in units:
pass 1 of 995units = [Fraction(1, i) for i in range(2, 11)]96for f1/2 in units[Fraction(1, 2), Fraction(1, 3), Fraction(1, 4), Fraction(1, 5), Fraction(1, 6), Fraction(1, 7), Fraction(1, 8), Fraction(1, 9), Fraction(1, 10)]:97 print(f"1/{f.denominator2} = {float(f1/2):.6f}")output1/2 = 0.500000All 9 passes — pass 1 is the card above pass ff.denominator1 1/2 2 2 1/3 3 3 1/4 4 4 1/5 5 5 1/6 6 6 1/7 7 7 1/8 8 8 1/9 9 9 1/10 10 frac ← 5/6, decomp ← 5/6, f1 ← 1/3, f2 ← 333/1000, diff ← 1/3000
99# Egyptian fractions comparison100print("\nEgyptian fractions (distinct unit fractions):")101# 5/6 = 1/2 + 1/3102frac→ 5/6 = Fraction(5, 6)103decomp→ 5/6 = Fraction(1, 2) + Fraction(1, 3)104print(f"{frac5/6} == 1/2 + 1/3: {frac == decomp5/6}")105106# Tolerance comparison (not usually needed)107print("\nTolerance comparison (for demonstration):")108f1→ 1/3 = Fraction(1, 3)109f2→ 333/1000 = Fraction(333, 1000) # Approximate 1/3110diff→ 1/3000 = abs(f11/3 - f2333/1000)111tolerance→ 1/100 = Fraction(1, 100)112approx_equal→ True = diff1/3000 <= tolerance1/100113print(f"{f11/3} ≈ {f2333/1000} (tolerance {tolerance1/100}): {approx_equalTrue}")114print(f"Difference: {diff1/3000}")output Egyptian fractions (distinct unit fractions): 5/6 == 1/2 + 1/3: True Tolerance comparison (for demonstration): 1/3 ≈ 333/1000 (tolerance 1/100): True Difference: 1/3000
Math Operations
Using fractions with math functions:
math.py
Replay: real traced execution (multi-file project)
# Mathematical operations
from fractions import Fraction
import math
# GCD and simplification
print("GCD and simplification:")
def show_gcd(a, b):
"""Show GCD and simplification."""
g = math.gcd(a, b)
print(f"gcd({a}, {b}) = {g}")
print(f" {a}/{b} = {a//g}/{b//g}")
show_gcd(6, 8)
show_gcd(12, 16)
show_gcd(100, 150)
print()
# LCM (least common multiple)
print("LCM for adding fractions:")
def show_lcm_addition(f1, f2):
"""Show LCM method for adding fractions."""
lcm = (f1.denominator * f2.denominator) // math.gcd(f1.denominator, f2.denominator)
print(f"{f1} + {f2}:")
print(f" LCM of {f1.denominator} and {f2.denominator} = {lcm}")
print(f" = {f1.numerator * (lcm // f1.denominator)}/{lcm} + {f2.numerator * (lcm // f2.denominator)}/{lcm}")
print(f" = {f1 + f2}")
show_lcm_addition(Fraction(1, 3), Fraction(1, 4))
show_lcm_addition(Fraction(2, 5), Fraction(3, 7))
print()
# Powers and roots
print("Powers:")
f = Fraction(2, 3)
for exp in range(1, 5):
result = f ** exp
print(f"({f})^{exp} = {result} = {float(result):.6f}")
print("\nNegative powers (reciprocals):")
for exp in range(1, 4):
result = f ** -exp
print(f"({f})^-{exp} = {result} = {float(result):.6f}")
print("\nSquare root (as float):")
f = Fraction(9, 16)
sqrt = math.sqrt(float(f))
print(f"√{f} = {sqrt}")
sqrt_frac = Fraction(3, 4) # Manual
print(f" = {sqrt_frac} (exact)")
# Series calculations
print("\nGeometric series:")
# Sum: a + ar + ar² + ar³ + ... (n terms)
def geometric_sum(a, r, n):
"""Sum of geometric series."""
if r == 1:
return a * n
return a * (1 - r**n) / (1 - r)
a = Fraction(1, 2)
r = Fraction(1, 2)
for n in [3, 5, 10]:
s = geometric_sum(a, r, n)
print(f"Sum of {n} terms (a={a}, r={r}): {s} = {float(s):.10f}")
# Approaching limit
print("\nApproaching limit (1 - 1/2^n):")
for n in range(1, 11):
limit = 1 - Fraction(1, 2**n)
print(f"n={n:2}: {limit} = {float(limit):.10f}")
# Fibonacci with fractions
print("\nFibonacci ratios:")
def fibonacci_ratio(n):
"""Get ratio of consecutive Fibonacci numbers."""
if n <= 1:
return None
a, b = Fraction(0), Fraction(1)
for _ in range(n):
a, b = b, a + b
return b / a if a != 0 else None
golden = (1 + math.sqrt(5)) / 2
print("Ratio of consecutive Fibonacci numbers (approaching φ):")
for n in range(5, 16):
ratio = fibonacci_ratio(n)
if ratio:
error = abs(float(ratio) - golden)
print(f"F({n})/F({n-1}) = {ratio.limit_denominator(10000)} ≈ {float(ratio):.10f} (error: {error:.2e})")
print(f"Golden ratio φ = {golden:.10f}")
# Harmonic mean
print("\nHarmonic mean:")
def harmonic_mean(nums):
"""Calculate harmonic mean."""
return len(nums) / sum(Fraction(1, x) for x in nums)
values = [Fraction(2), Fraction(3), Fraction(4)]
hm = harmonic_mean(values)
print(f"Harmonic mean of {[float(v) for v in values]}: {hm} = {float(hm):.6f}")
# Egyptian fractions
print("\nEgyptian fraction decomposition:")
def egyptian_fractions(frac, max_terms=10):
"""Decompose fraction into sum of unit fractions."""
terms = []
remaining = frac
n = 2
while remaining > 0 and len(terms) < max_terms:
unit = Fraction(1, n)
if unit <= remaining:
terms.append(n)
remaining -= unit
n += 1
if remaining == 0:
break
return terms
f = Fraction(5, 6)
decomp = egyptian_fractions(f)
print(f"{f} = {' + '.join(f'1/{d}' for d in decomp)}")
# Verify
verify = sum(Fraction(1, d) for d in decomp)
print(f"Verify: {verify}")
# Mediant
print("\nMediant (between two fractions):")
def mediant(f1, f2):
"""Calculate mediant of two fractions."""
return Fraction(f1.numerator + f2.numerator, f1.denominator + f2.denominator)
a, b = Fraction(1, 3), Fraction(1, 2)
m = mediant(a, b)
print(f"Mediant of {a} and {b}: {m} = {float(m):.6f}")
print(f"Check: {float(a):.6f} < {float(m):.6f} < {float(b):.6f}")
print("GCD and simplification:")
6# GCD and simplification7print("GCD and simplification:")89def show_gcd(a, b):10 """Show GCD and simplification."""11 g = math.gcd(a, b)12 print(f"gcd({a}, {b}) = {g}")13 print(f" {a}/{b} = {a//g}/{b//g}")1415show_gcd(6, 8)16show_gcd(12, 16)outputGCD and simplification:g ← 2
pass 1 of 39def show_gcd(a6, b8):10 """Show GCD and simplification."""11 g→ 2 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(a6, b8)12 print(f"gcd({a6}, {b8}) = {g2}")13 print(f" {a6}/{b8} = {a//g2}/{b//g}")outputgcd(6, 8) = 2 6/8 = 3/4All 3 passes — pass 1 is the card above pass abg1 6 8 2 2 12 16 4 3 100 150 50 show_gcd(6, 8)
15show_gcd(6, 8)16show_gcd(12, 16)17show_gcd(100, 150)show_gcd(12, 16)
15show_gcd(6, 8)16show_gcd(12, 16)17show_gcd(100, 150)18print()show_gcd(100, 150)
16show_gcd(12, 16)17show_gcd(100, 150)18print()1920# LCM (least common multiple)21print("LCM for adding fractions:")22def show_lcm_addition(f1, f2):23 """Show LCM method for adding fractions."""24 lcm = (f1.denominator * f2.denominator) // math.gcd(f1.denominator, f2.denominator)25 print(f"{f1} + {f2}:")26 print(f" LCM of {f1.denominator} and {f2.denominator} = {lcm}")27 print(f" = {f1.numerator * (lcm // f1.denominator)}/{lcm} + {f2.numerator * (lcm // f2.denominator)}/{lcm}")28 print(f" = {f1 + f2}")2930show_lcm_addition(Fraction(1, 3), Fraction(1, 4))31show_lcm_addition(Fraction(2, 5), Fraction(3, 7))outputLCM for adding fractions:lcm ← 12
pass 1 of 221print("LCM for adding fractions:")22def show_lcm_addition(f11/3, f21/4):23 """Show LCM method for adding fractions."""24 lcm→ 12 = (f1.denominator3 * f2.denominator4) // math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(f1.denominator, f2.denominator)25 print(f"{f11/3} + {f21/4}:")26 print(f" LCM of {f1.denominator3} and {f2.denominator4} = {lcm12}")27 print(f" = {f1.numerator1 * (lcm12 // f1.denominator3)}/{lcm} + {f2.numerator1 * (lcm // f2.denominator4)}/{lcm}")28 print(f" = {f11/3 + f21/4}")output1/3 + 1/4: LCM of 3 and 4 = 12 = 4/12 + 3/12 = 7/12show_lcm_addition(Fraction(1, 3), Fraction(1, 4))
30show_lcm_addition(Fraction(1, 3), Fraction(1, 4))31show_lcm_addition(Fraction(2, 5), Fraction(3, 7))32print()lcm ← 35
pass 2 of 221print("LCM for adding fractions:")22def show_lcm_addition(f12/5, f23/7):23 """Show LCM method for adding fractions."""24 lcm→ 35 = (f1.denominator5 * f2.denominator7) // math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.gcd(f1.denominator, f2.denominator)25 print(f"{f12/5} + {f23/7}:")26 print(f" LCM of {f1.denominator5} and {f2.denominator7} = {lcm35}")27 print(f" = {f1.numerator2 * (lcm35 // f1.denominator5)}/{lcm} + {f2.numerator3 * (lcm // f2.denominator7)}/{lcm}")28 print(f" = {f12/5 + f23/7}")output2/5 + 3/7: LCM of 5 and 7 = 35 = 14/35 + 15/35 = 29/35f ← 2/3
30show_lcm_addition(Fraction(1, 3), Fraction(1, 4))31show_lcm_addition(Fraction(2, 5), Fraction(3, 7))32print()3334# Powers and roots35print("Powers:")36f→ 2/3 = Fraction(2, 3)37for exp in range(1, 5):outputPowers:result ← 2/3
pass 1 of 436f = Fraction(2, 3)37for exp1 in range(1, 5):38 result→ 2/3 = f2/3 ** exp139 print(f"({f2/3})^{exp1} = {result2/3} = {float(result):.6f}")output(2/3)^1 = 2/3 = 0.666667All 4 passes — pass 1 is the card above pass expresult1 1 2/3 2 2 4/9 3 3 8/27 4 4 16/81 print(" Negative powers (reciprocals):")
41print("\nNegative powers (reciprocals):")42for exp in range(1, 4):output Negative powers (reciprocals):result ← 3/2
pass 1 of 341print("\nNegative powers (reciprocals):")42for exp1 in range(1, 4):43 result→ 3/2 = f2/3 ** -exp144 print(f"({f2/3})^-{exp1} = {result3/2} = {float(result):.6f}")output(2/3)^-1 = 3/2 = 1.500000All 3 passes — pass 1 is the card above pass expresult1 1 3/2 2 2 9/4 3 3 27/8 f ← 9/16, sqrt ← 0.75, sqrt_frac ← 3/4, a ← 1/2, r ← 1/2
46print("\nSquare root (as float):")47f→ 9/16 = Fraction(9, 16)48sqrt→ 0.75 = math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(float(f9/16))49print(f"√{f9/16} = {sqrt0.75}")50sqrt_frac→ 3/4 = Fraction(3, 4) # Manual51print(f" = {sqrt_frac3/4} (exact)")5253# Series calculations54print("\nGeometric series:")55# Sum: a + ar + ar² + ar³ + ... (n terms)56def geometric_sum(a, r, n):57 """Sum of geometric series."""58 if r == 1:59 return a * n60 return a * (1 - r**n) / (1 - r)6162a→ 1/2 = Fraction(1, 2)63r→ 1/2 = Fraction(1, 2)64for n in [3, 5, 10]:output Square root (as float): √9/16 = 0.75 = 3/4 (exact) Geometric series:for n in [3, 5, 10]:
pass 1 of 363r = Fraction(1, 2)64for n3 in [3, 5, 10]:65 s = geometric_sum(a1/2, r1/2, n3)66 print(f"Sum of {n} terms (a={a}, r={r}): {s} = {float(s):.10f}")All 3 passes — pass 1 is the card above pass n1 3 2 5 3 10 def geometric_sum(a, r, n):
pass 1 of 355# Sum: a + ar + ar² + ar³ + ... (n terms)56def geometric_sum(a1/2, r1/2, n3):57 """Sum of geometric series."""58 if r == 1:59 return a * n60 return a1/2 * (1 - r1/2**n3) / (1 - r)All 3 passes — pass 1 is the card above pass n1 3 2 5 3 10 s ← 7/8
64for n in [3, 5, 10]:65 s→ 7/8 = geometric_sum(a1/2, r1/2, n3)66 print(f"Sum of {n3} terms (a={a1/2}, r={r1/2}): {s7/8} = {float(s):.10f}")outputSum of 3 terms (a=1/2, r=1/2): 7/8 = 0.8750000000s ← 31/32
64for n in [3, 5, 10]:65 s→ 31/32 = geometric_sum(a1/2, r1/2, n5)66 print(f"Sum of {n5} terms (a={a1/2}, r={r1/2}): {s31/32} = {float(s):.10f}")outputSum of 5 terms (a=1/2, r=1/2): 31/32 = 0.9687500000s ← 1023/1024
64for n in [3, 5, 10]:65 s→ 1023/1024 = geometric_sum(a1/2, r1/2, n10)66 print(f"Sum of {n10} terms (a={a1/2}, r={r1/2}): {s1023/1024} = {float(s):.10f}")outputSum of 10 terms (a=1/2, r=1/2): 1023/1024 = 0.9990234375print(" Approaching limit (1 - 1/2^n):")
68# Approaching limit69print("\nApproaching limit (1 - 1/2^n):")70for n in range(1, 11):output Approaching limit (1 - 1/2^n):limit ← 1/2
pass 1 of 1069print("\nApproaching limit (1 - 1/2^n):")70for n1 in range(1, 11):71 limit→ 1/2 = 1 - Fraction(1, 2**n1)72 print(f"n={n1:2}: {limit1/2} = {float(limit):.10f}")outputn= 1: 1/2 = 0.5000000000All 10 passes — pass 1 is the card above pass nlimit1 1 1/2 2 2 3/4 3 3 7/8 4 4 15/16 5 5 31/32 6 6 63/64 7 7 127/128 8 8 255/256 9 9 511/512 10 10 1023/1024 golden ← 1.618033988749895
74# Fibonacci with fractions75print("\nFibonacci ratios:")76def fibonacci_ratio(n):77 """Get ratio of consecutive Fibonacci numbers."""78 if n <= 1:79 return None80 a, b = Fraction(0), Fraction(1)81 for _ in range(n):82 a, b = b, a + b83 return b / a if a != 0 else None8485golden→ 1.618033988749895 = (1 + math<module 'math' from '/usr/local/lib/python3.12/lib-dynload/math.cpython-312-x86_64-linux-gnu.so'>.sqrt(5)) / 286print("Ratio of consecutive Fibonacci numbers (approaching φ):")87for n in range(5, 16):output Fibonacci ratios: Ratio of consecutive Fibonacci numbers (approaching φ):for n in range(5, 16):
pass 1 of 1186print("Ratio of consecutive Fibonacci numbers (approaching φ):")87for n5 in range(5, 16):88 ratio = fibonacci_ratio(n5)89 if ratio:All 11 passes — pass 1 is the card above pass n1 5 2 6 3 7 4 8 5 9 6 10 7 11 8 12 9 13 10 14 11 15 a ← 0, b ← 1
pass 1 of 1175print("\nFibonacci ratios:")76def fibonacci_ratio(n5):77 """Get ratio of consecutive Fibonacci numbers."""78 if n <= 1:79 return None80 a→ 0, b→ 1 = Fraction(0), Fraction(1)81 for _ in range(n):All 11 passes — pass 1 is the card above pass nab1 5 0 1 2 6 0 1 3 7 0 1 4 8 0 1 5 9 0 1 6 10 0 1 7 11 0 1 8 12 0 1 9 13 0 1 10 14 0 1 11 15 0 1 a ← 1, b ← 1
pass 1 of 11080a, b = Fraction(0), Fraction(1)81for _0 in range(n5):82 a→ 1, b→ 1 = b, a + b83return b / a if a != 0 else None110 passes — pass 1 is the card above pass _nab1 0 5 0 → 1 1 2 1 5 1 1 → 2 3 2 5 1 → 2 2 → 3 4 3 5 2 → 3 3 → 5 5 4 5 3 → 5 5 → 8 6 0 6 0 → 1 1 7 1 6 1 1 → 2 8 2 6 1 → 2 2 → 3 9 3 6 2 → 3 3 → 5 ⋯ 99 more passes ⋯ 109 13 15 233 → 377 377 → 610 110 14 15 377 → 610 610 → 987 return b / a if a != 0 else None
82 a, b = b, a + b83return b8 / a5 if a != 0 else Noneratio ← 8/5
87for n in range(5, 16):88 ratio→ 8/5 = fibonacci_ratio(n5)89 if ratio:error ← 0.018033988749894814
pass 1 of 1188 ratio = fibonacci_ratio(n)89 if ratio8/5:90 error→ 0.018033988749894814 = abs(float(ratio8/5) - golden1.618033988749895)91 print(f"F({n5})/F({n-1}) = {ratio8/5.limit_denominator(10000)} ≈ {float(ratio):.10f} (error: {error0.018033988749894814:.2e})")92print(f"Golden ratio φ = {golden:.10f}")outputF(5)/F(4) = 8/5 ≈ 1.6000000000 (error: 1.80e-02)All 11 passes — pass 1 is the card above pass rationerror1 8/5 5 0.018033988749894814 2 13/8 6 0.0069660112501050975 3 21/13 7 0.0026493733652794837 4 34/21 8 0.0010136302977241662 5 55/34 9 0.00038692992636546464 6 89/55 10 0.00014782943192326314 7 144/89 11 5.6460660007306984e-05 8 233/144 12 2.15668056606777e-05 9 377/233 13 8.237676933475768e-06 10 610/377 14 3.1465286196574738e-06 11 987/610 15 1.2018646489142526e-06 return b / a if a != 0 else None
82 a, b = b, a + b83return b13 / a8 if a != 0 else Noneratio ← 13/8
87for n in range(5, 16):88 ratio→ 13/8 = fibonacci_ratio(n6)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b21 / a13 if a != 0 else Noneratio ← 21/13
87for n in range(5, 16):88 ratio→ 21/13 = fibonacci_ratio(n7)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b34 / a21 if a != 0 else Noneratio ← 34/21
87for n in range(5, 16):88 ratio→ 34/21 = fibonacci_ratio(n8)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b55 / a34 if a != 0 else Noneratio ← 55/34
87for n in range(5, 16):88 ratio→ 55/34 = fibonacci_ratio(n9)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b89 / a55 if a != 0 else Noneratio ← 89/55
87for n in range(5, 16):88 ratio→ 89/55 = fibonacci_ratio(n10)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b144 / a89 if a != 0 else Noneratio ← 144/89
87for n in range(5, 16):88 ratio→ 144/89 = fibonacci_ratio(n11)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b233 / a144 if a != 0 else Noneratio ← 233/144
87for n in range(5, 16):88 ratio→ 233/144 = fibonacci_ratio(n12)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b377 / a233 if a != 0 else Noneratio ← 377/233
87for n in range(5, 16):88 ratio→ 377/233 = fibonacci_ratio(n13)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b610 / a377 if a != 0 else Noneratio ← 610/377
87for n in range(5, 16):88 ratio→ 610/377 = fibonacci_ratio(n14)89 if ratio:return b / a if a != 0 else None
82 a, b = b, a + b83return b987 / a610 if a != 0 else Noneratio ← 987/610
87for n in range(5, 16):88 ratio→ 987/610 = fibonacci_ratio(n15)89 if ratio:values ← [Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)]
91 print(f"F({n})/F({n-1}) = {ratio.limit_denominator(10000)} ≈ {float(ratio):.10f} (error: {error:.2e})")92print(f"Golden ratio φ = {golden1.618033988749895:.10f}")9394# Harmonic mean95print("\nHarmonic mean:")96def harmonic_mean(nums):97 """Calculate harmonic mean."""98 return len(nums) / sum(Fraction(1, x) for x in nums)99100values→ [Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)] = [Fraction(2), Fraction(3), Fraction(4)]101hm = harmonic_mean(values[Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)])102print(f"Harmonic mean of {[float(v) for v in values]}: {hm} = {float(hm):.6f}")outputGolden ratio φ = 1.6180339887 Harmonic mean:def harmonic_mean(nums):
95print("\nHarmonic mean:")96def harmonic_mean(nums[Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)]):97 """Calculate harmonic mean."""98 return len(nums[Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)]) / sum(Fraction(1, x) for x in nums)hm ← 36/13, f ← 5/6
100values = [Fraction(2), Fraction(3), Fraction(4)]101hm→ 36/13 = harmonic_mean(values[Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)])102print(f"Harmonic mean of {[float(v) for v in values[Fraction(2, 1), Fraction(3, 1), Fraction(4, 1)]]}: {hm36/13} = {float(hm):.6f}")103104# Egyptian fractions105print("\nEgyptian fraction decomposition:")106def egyptian_fractions(frac, max_terms=10):107 """Decompose fraction into sum of unit fractions."""108 terms = []109 remaining = frac110 n = 2111 while remaining > 0 and len(terms) < max_terms:112 unit = Fraction(1, n)113 if unit <= remaining:114 terms.append(n)115 remaining -= unit116 n += 1117 if remaining == 0:118 break119 return terms120121f→ 5/6 = Fraction(5, 6)122decomp = egyptian_fractions(f5/6)123print(f"{f} = {' + '.join(f'1/{d}' for d in decomp)}")outputHarmonic mean of [2.0, 3.0, 4.0]: 36/13 = 2.769231 Egyptian fraction decomposition:terms ← [], remaining ← 5/6, n ← 2
105print("\nEgyptian fraction decomposition:")106def egyptian_fractions(frac5/6, max_terms10=10):107 """Decompose fraction into sum of unit fractions."""108 terms→ [] = []109 remaining→ 5/6 = frac5/6110 n→ 2 = 2111 while remaining > 0 and len(terms) < max_terms:unit ← 1/2
pass 1 of 2110n = 2111while remaining5/6 > 0 and len(terms[]) < max_terms10:112 unit→ 1/2 = Fraction(1, n2)113 if unit <= remaining:terms ← [2], remaining ← 1/3
pass 1 of 2112unit = Fraction(1, n)113if unit1/2 <= remaining5/6:114 terms→ [2].append(n2)115 remaining→ 1/3 -= unit1/2116n += 1n ← 3
115 remaining -= unit116n→ 3 += 1117if remaining == 0:unit ← 1/3
pass 2 of 2110n = 2111while remaining1/3 > 0 and len(terms[2]) < max_terms10:112 unit→ 1/3 = Fraction(1, n3)113 if unit <= remaining:terms ← [2, 3], remaining ← 0
pass 2 of 2112unit = Fraction(1, n)113if unit1/3 <= remaining1/3:114 terms→ [2, 3].append(n3)115 remaining→ 0 -= unit1/3116n += 1n ← 4
115 remaining -= unit116n→ 4 += 1117if remaining == 0:if remaining == 0:
116 n += 1117 if remaining0 == 0:118 break119return termsreturn terms
118 break119return terms[2, 3]decomp ← [2, 3], verify ← 5/6, a ← 1/3, b ← 1/2
121f = Fraction(5, 6)122decomp→ [2, 3] = egyptian_fractions(f5/6)123print(f"{f5/6} = {' + '.join(f'1/{d}' for d in decomp[2, 3])}")124# Verify125verify→ 5/6 = sum(Fraction(1, d) for d in decomp[2, 3])126print(f"Verify: {verify5/6}")127128# Mediant129print("\nMediant (between two fractions):")130def mediant(f1, f2):131 """Calculate mediant of two fractions."""132 return Fraction(f1.numerator + f2.numerator, f1.denominator + f2.denominator)133134a→ 1/3, b→ 1/2 = Fraction(1, 3), Fraction(1, 2)135m = mediant(a1/3, b1/2)136print(f"Mediant of {a} and {b}: {m} = {float(m):.6f}")output5/6 = 1/2 + 1/3 Verify: 5/6 Mediant (between two fractions):def mediant(f1, f2):
129print("\nMediant (between two fractions):")130def mediant(f11/3, f21/2):131 """Calculate mediant of two fractions."""132 return Fraction(f1.numerator1 + f2.numerator1, f1.denominator3 + f2.denominator2)m ← 2/5
134a, b = Fraction(1, 3), Fraction(1, 2)135m→ 2/5 = mediant(a1/3, b1/2)136print(f"Mediant of {a1/3} and {b1/2}: {m2/5} = {float(m):.6f}")137print(f"Check: {float(a1/3):.6f} < {float(m2/5):.6f} < {float(b1/2):.6f}")outputMediant of 1/3 and 1/2: 2/5 = 0.400000 Check: 0.333333 < 0.400000 < 0.500000
Exercise: practical.py
Scale a recipe by a fraction and calculate total ingredient amounts