Rationals

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 the Fraction 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 is 0 then the leading characters are used to recognize the base, this is done separately for the numerator and denominator. If base=10, any string that represents a finite value and is accepted by the float 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.

from_float(f, /) mpq

Converts a finite float 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

mpq Functions

gmpy2.qdiv(x, y=1, /) mpz | mpq

Return x/y as mpz if possible, or as mpq if x is not exactly divisible by y.