Next: , Previous: , Up: Internals   [Index]


16.2 Rational Internals

mpq_t variables represent rationals using an mpz_t numerator and denominator (see Integer Internals).

The canonical form adopted is denominator positive (and non-zero), no common factors between numerator and denominator, and zero uniquely represented as 0/1.

It’s believed that casting out common factors at each stage of a calculation is best in general. A GCD is an O(N^2) operation so it’s better to do a few small ones immediately than to delay and have to do a big one later. Knowing the numerator and denominator have no common factors can be used for example in mpq_mul to make only two cross GCDs necessary, not four.

This general approach to common factors is badly sub-optimal in the presence of simple factorizations or little prospect for cancellation, but GMP has no way to know when this will occur. As per Efficiency, that’s left to applications. The mpq_t framework might still suit, with mpq_numref and mpq_denref for direct access to the numerator and denominator, or of course mpz_t variables can be used directly.