Python 3.8+Numbers & mathfunction
int.as_integer_ratio
as a fraction
Return a pair (numerator, denominator) with denominator 1 — the integer as a ratio.
Syntax
n.as_integer_ratio()
The method computes nothing on its own — the denominator is always 1; it exists so that int, float, Decimal and Fraction can be handled through one interface without branching on type. It was added in Python 3.8, so older versions lack it on int. Do not expect a human-looking fraction from float.as_integer_ratio() either: it gives the exact binary value, so 0.1 comes back with a huge power of two as the denominator, not 10.
Examples
print((5).as_integer_ratio()) # → (5, 1)
print((-8).as_integer_ratio()) # → (-8, 1)
print((0).as_integer_ratio()) # → (0, 1)
print(True.as_integer_ratio()) # → (1, 1)
a, b = (3).as_integer_ratio(), (0.75).as_integer_ratio()
print(a, b) # → (3, 1) (3, 4)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy