5.4 Rational numbers
A rational number is a fraction. You learned about fractions early in your mathematical education. We use Fraction from the fractions module to create them.
from fractions import Fraction
Fraction(6, 5)
Fraction(6, 5)
f = Fraction(20, 30)
f
Fraction(2, 3)
Python stores a fraction in the lowest terms, which means the numerator and denominator have no common prime factors. Another way to say this is that the numerator and denominator have a greatest common divisor equal to 1.
f.numerator
2
f.denominator
3
import math
math.gcd(f.numerator, f.denominator)
1
Look carefully at the last expression and note that I wrote f.numerator
instead
of f.numerator()
. Instead of calling numerator
as a method, I asked for the “numerator property” of the fraction. A property is an
intrinsic part or characteristic of an object...