Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Arithmetic (Rational)

The four operations, the comparisons and the in-place forms are all exact. Multiplication and division reduce across the two fractions before multiplying, so the intermediates stay near the size of the answer rather than growing to the product of the denominators.

print(Rational(1, 2) + Rational(1, 3))     # 5/6
print(Rational(1, 2) / Rational(1, 3))     # 3/2
print(Rational(1, 3) < Rational(1, 2))     # True

var x = Rational(1, 2)
x += Rational(1, 3)                        # 5/6
x **= 3                                    # 125/216

A power takes a whole exponent, which may be negative:

print(Rational(3, 2) ** 7)                 # 2187/128
print(Rational(3, 2) ** -2)                # 4/9

A fractional exponent is not accepted. Python’s Fraction answers one with a float, which throws away the exactness the type exists for; ask BigFloat for that answer instead, where the precision is yours to choose.