The use of rational numbers with unbounded integers allows for exact
integer or fixed point arithmetic under addition, subtraction,
multiplication, division and exponentiation (^/2).
Support for rational numbers depends on the Prolog flag
prefer_rationals.
If this is true
(default), the number division function (//2)
and exponentiation function (^/2)
generate a rational number on integer and rational arguments and read/1
and friends read [-+][0-9_ ]+/[0-9_ ]+
into a rational
number. See also section
2.16.1.6. Here are some examples.
A is 2/6 | A = 1/3 |
A is 4/3 + 1 | A = 7/3 |
A is 4/3 + 1.5 | A = 2.83333 |
A is 4/3 + rationalize(1.5) | A = 17/6 |
Note that floats cannot represent all decimal numbers exactly. The function rational/1 creates an exact equivalent of the float, while rationalize/1 creates a rational number that is within the float rounding error from the original float. Please check the documentation of these functions for details and examples.
Rational numbers can be printed as decimal numbers with arbitrary precision using the format/3 floating point conversion:
?- A is 4/3 + rational(1.5), format('~50f~n', [A]). 2.83333333333333333333333333333333333333333333333333 A = 17/6