mpq.rst
1 Multiple-precision Rationals 2 ============================ 3 4 gmpy2 provides a rational type call *mpq*. It should be a replacement for 5 Python's fractions.Fraction module. 6 7 :: 8 9 >>> import gmpy2 10 >>> from gmpy2 import mpq 11 >>> mpq(1,7) 12 mpq(1,7) 13 >>> mpq(1,7) * 11 14 mpq(11,7) 15 >>> mpq(11,7)/13 16 mpq(11,91) 17 18 mpq Methods 19 ----------- 20 21 **digits(...)** 22 x.digits([base=10]) returns a Python string representing *x* in the 23 given base (2 to 62, default is 10). A leading '-' is present if *x* < 0, 24 but no leading '+' is present if *x* >= 0. 25 26 mpq Attributes 27 -------------- 28 29 **denominator** 30 x.denominator returns the denominator of *x*. 31 32 **numerator** 33 x.numerator returns the numerator of *x*. 34 35 mpq Functions 36 ------------- 37 38 **add(...)** 39 add(x, y) returns *x* + *y*. The result type depends on the input 40 types. 41 42 **div(...)** 43 div(x, y) returns *x* / *y*. The result type depends on the input 44 types. 45 46 **f2q(...)** 47 f2q(x[, err]) returns the best *mpq* approximating *x* to within 48 relative error *err*. Default is the precision of *x*. If *x* is not an 49 *mpfr*, it is converted to an *mpfr*. Uses Stern-Brocot tree to find the 50 best approximation. An *mpz* is returned if the denominator is 1. If 51 *err* < 0, then the relative error sought is 2.0 ** *err*. 52 53 **mpq(...)** 54 mpq() returns an *mpq* object set to 0/1. 55 56 mpq(n) returns an *mpq* object with a numeric value *n*. Decimal and 57 Fraction values are converted exactly. 58 59 mpq(n, m) returns an *mpq* object with a numeric value *n* / *m*. 60 61 mpq(s[, base=10]) returns an *mpq* object from a string *s* made up of 62 digits in the given base. *s* may be made up of two numbers in the same 63 base separated by a '/' character. If *base* == 10, then an embedded '.' 64 indicates a number with a decimal fractional part. 65 66 **mul(...)** 67 mul(x, y) returns *x* \* *y*. The result type depends on the input 68 types. 69 70 **qdiv(...)** 71 qdiv(x[, y=1]) returns *x/y* as *mpz* if possible, or as *mpq* if *x* 72 is not exactly divisible by *y*. 73 74 **sub(...)** 75 sub(x, y) returns *x* - *y*. The result type depends on the input 76 types. 77 78 79 80