Arithmetic (Rational)
Examples on this page assume from decimo.prelude import * and run inside def main() raises:.
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.
Built from decimo main. This page in the manual.