fractions.Fraction

class fractions.Fraction[source]

This class implements rational numbers.

In the two-argument form of the constructor, Fraction(8, 6) will produce a rational number equivalent to 4/3. Both arguments must be Rational. The numerator defaults to 0 and the denominator defaults to 1 so that Fraction(3) == 3 and Fraction() == 0.

Fractions can also be constructed from:

  • numeric strings similar to those accepted by the float constructor (for example, ‘-2.3’ or ‘1e10’)
  • strings of the form ‘123/456’
  • float and Decimal instances
  • other Rational instances (including integers)

Methods

__abs__(a)
__add__(a, b) a + b
__complex__(self) == complex(float(self), 0)
__copy__()
__deepcopy__(memo)
__div__(a, b) a / b
__divmod__(other) divmod(self, other): The pair (self // other, self % other).
__eq__(a, b) a == b
__float__() float(self) = self.numerator / self.denominator
__floordiv__(a, b) a // b
__format__ default object formatter
__ge__(a, b) a >= b
__gt__(a, b) a > b
__hash__(self) Tricky because values that are exactly representable as a float must have the same hash as that float.
__le__(a, b) a <= b
__lt__(a, b) a < b
__mod__(a, b) a % b
__mul__(a, b) a * b
__ne__(other) self != other
__neg__(a) -a
__new__([numerator, denominator]) Constructs a Fraction.
__nonzero__(a) a != 0
__pos__(a) +a: Coerces a subclass instance to Fraction
__pow__(a, b) a ** b
__radd__(b, a) a + b
__rdiv__(b, a) a / b
__rdivmod__(other) divmod(other, self): The pair (self // other, self % other).
__reduce__()
__reduce_ex__ helper for pickle
__repr__(self)
__rfloordiv__(b, a) a // b
__rmod__(b, a) a % b
__rmul__(b, a) a * b
__rpow__(b, a) a ** b
__rsub__(b, a) a - b
__rtruediv__(b, a) a / b
__sizeof__(() -> int) size of object in memory, in bytes
__str__(self)
__sub__(a, b) a - b
__subclasshook__ Abstract classes can override this to customize issubclass().
__truediv__(a, b) a / b
__trunc__(a)
_add(a, b) a + b
_div(a, b) a / b
_mul(a, b) a * b
_operator_fallbacks(monomorphic_operator, ...) Generates forward and reverse operators given a purely-rational operator and a function from the operator module.
_richcmp(other, op) Helper for comparison operators, for internal use only.
_sub(a, b) a - b
conjugate() Conjugate is a no-op for Reals.
from_decimal(dec) Converts a finite Decimal instance to a rational number, exactly.
from_float(f) Converts a finite float to a rational number, exactly.
limit_denominator([max_denominator]) Closest Fraction to self with denominator at most max_denominator.

Attributes

denominator
imag Real numbers have no imaginary component.
numerator
real Real numbers are their real component.