## 6 Rational Number Functions ¶

This chapter describes the GMP functions for performing arithmetic on rational numbers. These functions start with the prefix `mpq_`.

Rational numbers are stored in objects of type `mpq_t`.

All rational arithmetic functions assume operands have a canonical form, and canonicalize their result. The canonical form means that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1.

Pure assignment functions do not canonicalize the assigned variable. It is the responsibility of the user to canonicalize the assigned variable before any arithmetic operations are performed on that variable.

Function: `void` mpq_canonicalize `(mpq_t op)` ¶

  Remove any factors that are common to the numerator and denominator of op, and make the denominator positive.

### 6.1 Initialization and Assignment Functions ¶

Function: `void` mpq_init `(mpq_t x)` ¶

  Initialize x and set it to 0/1. Each variable should normally only be initialized once, or at least cleared out (using the function `mpq_clear`) between each initialization.

Function: `void` mpq_inits `(mpq_t x, ...)` ¶

  Initialize a NULL-terminated list of `mpq_t` variables, and set their values to 0/1.

Function: `void` mpq_clear `(mpq_t x)` ¶

  Free the space occupied by x. Make sure to call this function for all `mpq_t` variables when you are done with them.

Function: `void` mpq_clears `(mpq_t x, ...)` ¶

  Free the space occupied by a NULL-terminated list of `mpq_t` variables.

Function: `void` mpq_set `(mpq_t rop, const mpq_t op)` ¶
Function: `void` mpq_set_z `(mpq_t rop, const mpz_t op)` ¶

  Assign rop from op.

Function: `void` mpq_set_ui `(mpq_t rop, unsigned long int op1, unsigned long int op2)` ¶
Function: `void` mpq_set_si `(mpq_t rop, signed long int op1, unsigned long int op2)` ¶

  Set the value of rop to op1/op2. Note that if op1 and op2 have common factors, rop has to be passed to `mpq_canonicalize` before any operations are performed on rop.

Function: `int` mpq_set_str `(mpq_t rop, const char *str, int base)` ¶

  Set rop from a null-terminated string str in the given base.

  The string can be an integer like “41” or a fraction like “41/152”. The fraction must be in canonical form (see Rational Number Functions), or if not then `mpq_canonicalize` must be called.

  The numerator and optional denominator are parsed the same as in `mpz_set_str` (see Assignment Functions). White space is allowed in the string, and is simply ignored. The base can vary from 2 to 62, or if base is 0 then the leading characters are used: `0x` or `0X` for hex, `0b` or `0B` for binary, `0` for octal, or decimal otherwise. Note that this is done separately for the numerator and denominator, so for instance `0xEF/100` is 239/100, whereas `0xEF/0x100` is 239/256.

  The return value is 0 if the entire string is a valid number, or −1 if not.

Function: `void` mpq_swap `(mpq_t rop1, mpq_t rop2)` ¶

  Swap the values rop1 and rop2 efficiently.

### 6.2 Conversion Functions ¶

Function: `double` mpq_get_d `(const mpq_t op)` ¶

  Convert op to a `double`, truncating if necessary (i.e. rounding towards zero).

  If the exponent from the conversion is too big or too small to fit a `double` then the result is system dependent. For too big an infinity is returned when available. For too small 0.0 is normally returned. Hardware overflow, underflow and denorm traps may or may not occur.

Function: `void` mpq_set_d `(mpq_t rop, double op)` ¶
Function: `void` mpq_set_f `(mpq_t rop, const mpf_t op)` ¶

  Set rop to the value of op. There is no rounding, this conversion is exact.

Function: `char *` mpq_get_str `(char *str, int base, const mpq_t op)` ¶

  Convert op to a string of digits in base base. The base argument may vary from 2 to 62 or from −2 to −36. The string will be of the form ‘`num/den`’, or if the denominator is 1 then just ‘`num`’.

  For base in the range 2..36, digits and lower-case letters are used; for −2..−36, digits and upper-case letters are used; for 37..62, digits, upper-case letters, and lower-case letters (in that significance order) are used.

  If str is `NULL`, the result string is allocated using the current allocation function (see Custom Allocation). The block will be `strlen(str)+1` bytes, that being exactly enough for the string and null-terminator.

  If str is not `NULL`, it should point to a block of storage large enough for the result, that being

      mpz_sizeinbase (mpq_numref(op), base)
      + mpz_sizeinbase (mpq_denref(op), base) + 3

  The three extra bytes are for a possible minus sign, possible slash, and the null-terminator.

  A pointer to the result string is returned, being either the allocated block, or the given str.

### 6.3 Arithmetic Functions ¶

Function: `void` mpq_add `(mpq_t sum, const mpq_t addend1, const mpq_t addend2)` ¶

  Set sum to addend1 + addend2.

Function: `void` mpq_sub `(mpq_t difference, const mpq_t minuend, const mpq_t subtrahend)` ¶

  Set difference to minuend − subtrahend.

Function: `void` mpq_mul `(mpq_t product, const mpq_t multiplier, const mpq_t multiplicand)` ¶

  Set product to multiplier times multiplicand.

Function: `void` mpq_mul_2exp `(mpq_t rop, const mpq_t op1, mp_bitcnt_t op2)` ¶

  Set rop to op1 times 2 raised to op2.

Function: `void` mpq_div `(mpq_t quotient, const mpq_t dividend, const mpq_t divisor)` ¶

  Set quotient to dividend/divisor.

Function: `void` mpq_div_2exp `(mpq_t rop, const mpq_t op1, mp_bitcnt_t op2)` ¶

  Set rop to op1 divided by 2 raised to op2.

Function: `void` mpq_neg `(mpq_t negated_operand, const mpq_t operand)` ¶

  Set negated_operand to −operand.

Function: `void` mpq_abs `(mpq_t rop, const mpq_t op)` ¶

  Set rop to the absolute value of op.

Function: `void` mpq_inv `(mpq_t inverted_number, const mpq_t number)` ¶

  Set inverted_number to 1/number. If the new denominator is zero, this routine will divide by zero.

### 6.4 Comparison Functions ¶

Function: `int` mpq_cmp `(const mpq_t op1, const mpq_t op2)` ¶
Function: `int` mpq_cmp_z `(const mpq_t op1, const mpz_t op2)` ¶

  Compare op1 and op2. Return a positive value if op1 > op2, zero if op1 = op2, and a negative value if op1 < op2.

  To determine if two rationals are equal, `mpq_equal` is faster than `mpq_cmp`.

Macro: `int` mpq_cmp_ui `(const mpq_t op1, unsigned long int num2, unsigned long int den2)` ¶
Macro: `int` mpq_cmp_si `(const mpq_t op1, long int num2, unsigned long int den2)` ¶

  Compare op1 and num2/den2. Return a positive value if op1 > num2/den2, zero if op1 = num2/den2, and a negative value if op1 < num2/den2.

  num2 and den2 are allowed to have common factors.

  These functions are implemented as macros and evaluate their arguments multiple times.

Macro: `int` mpq_sgn `(const mpq_t op)` ¶

  Return +1 if op > 0, 0 if op = 0, and -1 if op < 0.

  This function is actually implemented as a macro. It evaluates its argument multiple times.

Function: `int` mpq_equal `(const mpq_t op1, const mpq_t op2)` ¶

  Return non-zero if op1 and op2 are equal, zero if they are non-equal. Although `mpq_cmp` can be used for the same purpose, this function is much faster.

### 6.5 Applying Integer Functions to Rationals ¶

The set of `mpq` functions is quite small. In particular, there are few functions for either input or output. The following functions give direct access to the numerator and denominator of an `mpq_t`.

Note that if an assignment to the numerator and/or denominator could take an `mpq_t` out of the canonical form described at the start of this chapter (see Rational Number Functions) then `mpq_canonicalize` must be called before any other `mpq` functions are applied to that `mpq_t`.

Macro: `mpz_ptr` mpq_numref `(const mpq_t op)` ¶
Macro: `mpz_ptr` mpq_denref `(const mpq_t op)` ¶

  Return a reference to the numerator and denominator of op, respectively. The `mpz` functions can be used on the result of these macros. Such calls may modify the numerator or denominator. However, care should be taken so that op remains in canonical form prior to a possible later call to an `mpq` function.

Function: `void` mpq_get_num `(mpz_t numerator, const mpq_t rational)` ¶
Function: `void` mpq_get_den `(mpz_t denominator, const mpq_t rational)` ¶
Function: `void` mpq_set_num `(mpq_t rational, const mpz_t numerator)` ¶
Function: `void` mpq_set_den `(mpq_t rational, const mpz_t denominator)` ¶

  Get or set the numerator or denominator of a rational. These functions are equivalent to calling `mpz_set` with an appropriate `mpq_numref` or `mpq_denref`. Direct use of `mpq_numref` or `mpq_denref` is recommended instead of these functions.

### 6.6 Input and Output Functions ¶

Functions that perform input from a stdio stream, and functions that output to a stdio stream, of `mpq` numbers. Passing a `NULL` pointer for a stream argument to any of these functions will make them read from `stdin` and write to `stdout`, respectively.

When using any of these functions, it is a good idea to include `stdio.h` before `gmp.h`, since that will allow `gmp.h` to define prototypes for these functions.

See also Formatted Output and Formatted Input.

Function: `size_t` mpq_out_str `(FILE *stream, int base, const mpq_t op)` ¶

  Output op on stdio stream stream, as a string of digits in base base. The base argument may vary from 2 to 62 or from −2 to −36. Output is in the form ‘`num/den`’ or if the denominator is 1 then just ‘`num`’.

  For base in the range 2..36, digits and lower-case letters are used; for −2..−36, digits and upper-case letters are used; for 37..62, digits, upper-case letters, and lower-case letters (in that significance order) are used.

  Return the number of bytes written, or if an error occurred, return 0.

Function: `size_t` mpq_inp_str `(mpq_t rop, FILE *stream, int base)` ¶

  Read a string of digits from stream and convert them to a rational in rop. Any initial white-space characters are read and discarded. Return the number of characters read (including white space), or 0 if a rational could not be read.

  The input can be a fraction like ‘`17/63`’ or just an integer like ‘`123`’. Reading stops at the first character not in this form, and white space is not permitted within the string. If the input might not be in canonical form, then `mpq_canonicalize` must be called (see Rational Number Functions).

  The base can be between 2 and 62, or can be 0 in which case the leading characters of the string determine the base, ‘`0x`’ or ‘`0X`’ for hexadecimal, `0b` and `0B` for binary, ‘`0`’ for octal, or decimal otherwise. The leading characters are examined separately for the numerator and denominator of a fraction, so for instance ‘`0x10/11`’ is 16/11, whereas ‘`0x10/0x11`’ is 16/17.