Multiple-precision Rationals
gmpy2 provides a rational type mpq
. It should be a replacement for
Python’s Fraction
class.
>>> from gmpy2 import mpq
>>> mpq(1,7)
mpq(1,7)
>>> mpq(1,7) * 11
mpq(11,7)
>>> mpq(11,7)/13
mpq(11,91)
mpq type
- class gmpy2.mpq(n=0, /)
- class gmpy2.mpq(n, m, /)
- class gmpy2.mpq(s, /, base=10)
Return a rational number constructed from a non-complex number n exactly or from a pair of
Rational
values n and m or from a string s made up of digits in the given base. Every input, that is accepted by theFraction
type constructor is also accepted.A string may be made up to two integers in the same base separated by a ‘/’ character, both parsed the same as the
mpz
type constructor does. If base=10, any string that represents a finite value and is accepted by thefloat
constructor is also accepted.- as_integer_ratio() tuple[mpz, mpz]
Return a pair of integers, whose ratio is exactly equal to the original number. The ratio is in lowest terms and has a positive denominator.
- conjugate() mpz
Return the conjugate of x (which is just a new reference to x since x is not a complex number).
- digits(base=10, /) str
Return a Python string representing x in the given base (2 to 62, default is 10). A leading ‘-’ is present if x<0, but no leading ‘+’ is present if x>=0.
- from_decimal(dec, /) mpq
Converts a finite
decimal.Decimal
instance to a rational number, exactly.
- denominator
the denominator of a rational number in lowest terms
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number