ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Rational.h File Reference

The exact rational numbers of Knuth (section 4.5.1 of The Art of Computer Programming), beyond the book: a fraction \( u / u' \) of integers of any length [see BigInteger.h] kept in lowest terms, with \( u' > 0 \). More...

#include "ADS/Contract.h"
#include "ADS/numeric/BigInteger.h"
#include <compare>
#include <concepts>
#include <cstddef>
#include <string>
#include <utility>
#include "ADS/numeric/impl/Rational.tpp"

Go to the source code of this file.

Classes

class  ADS::Rational
 a fraction in lowest terms, the denominator positive More...

Namespaces

namespace  ADS

Macros

#define ADS_RATIONAL_GMP   ADS_BIGINT_GMP

Detailed description

The exact rational numbers of Knuth (section 4.5.1 of The Art of Computer Programming), beyond the book: a fraction \( u / u' \) of integers of any length [see BigInteger.h] kept in lowest terms, with \( u' > 0 \).

The sum and the product reduce by the greatest common divisors of the smaller numbers, as Henrici suggested, instead of by that of the result: for \( u / u' + v / v' \), with \( d_1 = \gcd( u' , v' ) \), the numerator is \( t = u ( v' / d_1 ) + v ( u' / d_1 ) \) and, with \( d_2 = \gcd( t , d_1 ) \), the result is \( ( t / d_2 ) / ( ( u' / d_1 ) ( v' / d_2 ) ) \), already in lowest terms; for the product, \( d_1 = \gcd( u , v' ) \) and \( d_2 = \gcd( u' , v ) \) cancel crosswise. Since \( d_1 = 1 \) with probability about \( 6 / \pi^2 \), the second gcd is most often skipped, as is a division by a gcd of 1.

With ADS_WITH_GMP [see BigInteger.h], every operation of two fractions, the sum, the difference, the product, the quotient and the comparison, goes to mpq_add(), mpq_sub(), mpq_mul(), mpq_div() and mpq_cmp() of GMP, which follow the same method of Henrici, at every length: GMP reads the terms as they are, in place, and the terms of the result are copied from the fraction of GMP that receives it; the reductions of the constructor go to GMP through the gcd and the exact quotient of BigInteger. Without the macro, and with ADS_RATIONAL_GMP defined to 0, Rational keeps the code of the book above on the operations of BigInteger [see The backends of GMP and of a CBLAS].

The contracts [see Contract.h]: the denominator and a divisor are not 0; the invariant is \( u' > 0 \) and \( \gcd( u , u' ) = 1 \), an audit. The operations are defined in Rational.tpp.

See also
D. E. Knuth, The Art of Computer Programming, vol. 2, 3rd ed., Addison-Wesley, 1998, section 4.5.1
T. Granlund and the GMP development team, GNU MP: The GNU Multiple Precision Arithmetic Library, version 6.3.0, 2023, https://gmplib.org/gmp-man-6.3.0.pdf, the layer mpq of the backend
Author
Donato Meoli
Dipartimento di Informatica
Università di Pisa

Macro definition documentation

◆ ADS_RATIONAL_GMP

#define ADS_RATIONAL_GMP   ADS_BIGINT_GMP