4.27.2.2 Rational number examples
The use of rational numbers with unbounded integers allows for exact integer or fixed point arithmetic under addition, subtraction, multiplication and division. To exploit rational arithmetic rdiv/2 should be used instead of `/' and floating point numbers must be converted to rational using rational/1. Omitting the rational/1 on floats will convert a rational operand to float and continue the arithmetic using floating point numbers. Here are some examples.
A is 2 rdiv 6 | A = 1 rdiv 3 |
A is 4 rdiv 3 + 1 | A = 7 rdiv 3 |
A is 4 rdiv 3 + 1.5 | A = 2.83333 |
A is 4 rdiv 3 + rational(1.5) | A = 17 rdiv 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 rdiv 3 + rational(1.5), format('~50f~n', [A]). 2.83333333333333333333333333333333333333333333333333 A = 17 rdiv 6