## 4.26 Arithmetic

Arithmetic can be divided into some special purpose integer predicates and a series of general predicates for integer, floating point and rational arithmetic as appropriate. The general arithmetic predicates all handle expressions. An expression is either a simple number or a function. The arguments of a function are expressions. The functions are described in section 4.26.2.3.

### 4.26.1 Special purpose integer arithmetic

The predicates in this section provide more logical operations between integers. They are not covered by the ISO standard, although they are `part of the community' and found as either library or built-in in many other Prolog systems.

between(+Low, +High, ?Value)
Low and High are integers, High >=Low. If Value is an integer, Low =<Value =<High. When Value is a variable it is successively bound to all integers between Low and High. If High is `inf` or `infinite`51We prefer `infinite`, but some other Prolog systems already use `inf` for infinity we accept both for the time being. between/3 is true iff Value >=Low, a feature that is particularly interesting for generating integers from a certain value.
succ(?Int1, ?Int2)
True if Int2 = Int1 + 1 and Int1 >= 0. At least one of the arguments must be instantiated to a natural number. This predicate raises the domain-error `not_less_than_zero` if called with a negative integer. E.g. `succ(X, 0)` fails silently and `succ(X, -1)` raises a domain-error.52The behaviour to deal with natural numbers only was defined by Richard O'Keefe to support the common count-down-to-zero in a natural way. Up-to 5.1.8 succ/2 also accepted negative integers.
plus(?Int1, ?Int2, ?Int3)
True if Int3 = Int1 + Int2. At least two of the three arguments must be instantiated to integers.

### 4.26.2 General purpose arithmetic

The general arithmetic predicates are optionally compiled (see set_prolog_flag/2 and the -O command line option). Compiled arithmetic reduces global stack requirements and improves performance. Unfortunately compiled arithmetic cannot be traced, which is why it is optional.

[ISO]+Expr1 > +Expr2
True if expression Expr1 evaluates to a larger number than Expr2.
[ISO]+Expr1 < +Expr2
True if expression Expr1 evaluates to a smaller number than Expr2.
[ISO]+Expr1 =< +Expr2
True if expression Expr1 evaluates to a smaller or equal number to Expr2.
[ISO]+Expr1 >= +Expr2
True if expression Expr1 evaluates to a larger or equal number to Expr2.
[ISO]+Expr1 =\= +Expr2
True if expression Expr1 evaluates to a number non-equal to Expr2.
[ISO]+Expr1 =:= +Expr2
True if expression Expr1 evaluates to a number equal to Expr2.
[ISO]-Number is +Expr
True if Number has successfully been unified with the number Expr evaluates to. If Expr evaluates to a float that can be represented using an integer (i.e, the value is integer and within the range that can be described by Prolog's integer representation), Expr is unified with the integer value.

Note that normally, is/2 should be used with unbound left operand. If equality is to be tested, =:=/2 should be used. For example:

 `?- 1 is sin(pi/2).` Fails!. sin(pi/2) evaluates to the float 1.0, which does not unify with the integer 1. `?- 1 =:= sin(pi/2).` Succeeds as expected.

#### 4.26.2.1 Arithmetic types

SWI-Prolog defines the following numeric types:

• integer
If SWI-Prolog is built using the GNU multiple precision arithmetic library (GMP), integer arithmetic is unbounded, which means that the size of integers is limited by available memory only. Without GMP, SWI-Prolog integers are 64-bits, regardless of the native integer size of the platform. The type of integer support can be detected using the Prolog flags bounded, min_integer and max_integer. As the use of GMP is default, most of the following descriptions assume unbounded integer arithmetic.

Internally, SWI-Prolog has three integer representations. Small integers (defined by the Prolog flag max_tagged_integer) are encoded directly. Larger integers are represented as 64-bit value on the global stack. Integers that do not fit in 64-bit are represented as serialised GNU MPZ structures on the global stack.

• rational number
Rational numbers (Q) are quotients of two integers. Rational arithmetic is only provided if GMP is used (see above). Rational numbers are currently not supported by a Prolog type. They are represented by the compound term `rdiv(N,M)`. Rational numbers that are returned from is/2 are canonical, which means M is positive and N and M have no common divisors. Rational numbers are introduced in the computation using the rational/1, rationalize/1 or the rdiv/2 (rational division) function. Using the same functor for rational division and representing rational numbers allow for passing rational numbers between computations as well as to format/3 for printing.

On the long term it is likely that rational numbers will become atomic as well as subtype of number. User code that creates or inspects the `rdiv(M,N)` terms will not be portable to future versions. Rationals are created using one of the functions mentioned above and inspected using rational/3.

• float
Floating point numbers are represented using the C-type `double`. On most today platforms these are 64-bit IEEE floating point numbers.

Arithmetic functions that require integer arguments accept, in addition to integers, rational numbers with denominator `1' and floating point numbers that can be accurately converted to integers. If the required argument is a float the argument is converted to float. Note that conversion of integers to floating point numbers may raise an overflow exception. In all other cases, arguments are converted to the same type using the order below.

integer -> rational number -> floating point number

#### 4.26.2.2 Rational number examples

The use of rational numbers with unbounded integers allows for exact integer or fixed point arithmetic under the 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
```

#### 4.26.2.3 Arithmetic Functions

Arithmetic functions are terms which are evaluated by the arithmetic predicates described in section 4.26.2. SWI-Prolog tries to hide the difference between integer arithmetic and floating point arithmetic from the Prolog user. Arithmetic is done as integer arithmetic as long as possible and converted to floating point arithmetic whenever one of the arguments or the combination of them requires it. If a function returns a floating point value which is whole it is automatically transformed into an integer. There are four types of arguments to functions:

 Expr Arbitrary expression, returning either a floating point value or an integer. IntExpr Arbitrary expression that must evaluate into an integer. RatExpr Arbitrary expression that must evaluate into a rational number. FloatExpr Arbitrary expression that must evaluate into a floating point.

For systems using bounded integer arithmetic (default is unbounded, see section 4.26.2.1 for details), integer operations that would cause overflow automatically convert to floating point arithmetic.

[ISO]- +Expr
Result = -Expr
+ +Expr
Result = Expr. Note that if `+` is followed by a number the parser discards the `+`. I.e. `?- integer(+1)` succeeds.
[ISO]+Expr1 + +Expr2
Result = Expr1 + Expr2
[ISO]+Expr1 - +Expr2
Result = Expr1 - Expr2
[ISO]+Expr1 * +Expr2
Result = Expr1 × Expr2
[ISO]+Expr1 / +Expr2
Result = Expr1/Expr2 The the flag iso is `true`, both arguments are converted to float and the return value is a float. Otherwise (default), if both arguments are integers the operation returns an integer if the division is exact. If at least one of the arguments is rational and the other argument is integer, the operation returns a rational number. In all other cases the return value is a float. See also ///2 and rdiv/2.
[ISO]+IntExpr1 mod +IntExpr2
Modulo: Result = IntExpr1 - (IntExpr1 div IntExpr2) × IntExpr2, where `div` is floored division.
[ISO]+IntExpr1 rem +IntExpr2
Remainder of integer division. Behaves as if defined by Result is IntExpr1 - (IntExpr1 // IntExpr2) × IntExpr2
[ISO]+IntExpr1 // +IntExpr2
Integer division: Result is truncate(Expr1/Expr2)
+RatExpr rdiv +RatExpr
Rational number division. This function is only available if SWI-Prolog has been compiled with rational number support. See section 4.26.2.2 for details.
[ISO]abs(+Expr)
Evaluate Expr and return the absolute value of it.
[ISO]sign(+Expr)
Evaluate to -1 if Expr < 0, 1 if Expr > 0 and 0 if Expr = 0.
max(+Expr1, +Expr2)
Evaluates to the largest of both Expr1 and Expr2. Both arguments are compared after converting to the same type, but the return value is in the original type. For example, max(2.5, 3) compares the two values after converting to float, but returns the integer 3.
min(+Expr1, +Expr2)
Evaluates to the smallest of both Expr1 and Expr2. See max/2 for a description of type-handling.
.(+Int,[])
A list of one element evaluates to the element. This implies `"a"` evaluates to the character code of the letter `a' (97). This option is available for compatibility only. It will not work if ``style_check(+string)`' is active as `"a"` will then be transformed into a string object. The recommended way to specify the character code of the letter `a' is `0'a`.
random(+IntExpr)
Evaluates to a random integer i for which 0 =< i < IntExpr. The seed of this random generator is determined by the system clock when SWI-Prolog was started.
[ISO]round(+Expr)
Evaluates Expr and rounds the result to the nearest integer.
integer(+Expr)
Same as round/1 (backward compatibility).
[ISO]float(+Expr)
Translate the result to a floating point number. Normally, Prolog will use integers whenever possible. When used around the 2nd argument of is/2, the result will be returned as a floating point number. In other contexts, the operation has no effect.
rational(+Expr)
Convert the Expr to a rational number or integer. The function returns the input on integers and rational numbers. For floating point numbers, the returned rational number exactly represents the float. As floats cannot exactly represent all decimal numbers the results may be surprising. In the examples below, doubles can represent 0.25 and the result is as expected, in contrast to the result of `rational(0.1)`. The function rationalize/1 remedies this. See section 4.26.2.2 for more information on rational number support.
```?- A is rational(0.25).

A is 1 rdiv 4
?- A is rational(0.1).
A = 3602879701896397 rdiv 36028797018963968
```
rationalize(+Expr)
Convert the Expr to a rational number or integer. The function is similar to rational/1, but the result is only accurate within the rounding error of floating point numbers, generally producing a much smaller denominator.53The names rational/1 and rationalize/1 as well as their semantics are inspired by Common Lisp.
```?- A is rationalize(0.25).

A = 1 rdiv 4
?- A is rationalize(0.1).

A = 1 rdiv 10
```
[ISO]float_fractional_part(+Expr)
Fractional part of a floating-point number. Negative if Expr is negative, rational if Expr is rational and 0 if Expr is integer. The following relation is always true: X is float_fractional_part(X) + float_integer_part(X).
[ISO]float_integer_part(+Expr)
Integer part of floating-point number. Negative if Expr is negative, Expr if Expr is integer.
[ISO]truncate(+Expr)
Truncate Expr to an integer. If Expr >= 0 this is the same as `floor(Expr)`. For Expr < 0 this is the same as `ceil(Expr)`. E.i. truncate rounds towards zero.
[ISO]floor(+Expr)
Evaluates Expr and returns the largest integer smaller or equal to the result of the evaluation.
[ISO]ceiling(+Expr)
Evaluates Expr and returns the smallest integer larger or equal to the result of the evaluation.
ceil(+Expr)
Same as ceiling/1 (backward compatibility).
[ISO]+IntExpr >> +IntExpr
Bitwise shift IntExpr1 by IntExpr2 bits to the right. The operation performs arithmetic shift, which implies that the inserted most significant bits are copies of the original most significant bit.
[ISO]+IntExpr << +IntExpr
Bitwise shift IntExpr1 by IntExpr2 bits to the left.
[ISO]+IntExpr \/ +IntExpr
Bitwise `or' IntExpr1 and IntExpr2.
[ISO]+IntExpr /\ +IntExpr
Bitwise `and' IntExpr1 and IntExpr2.
+IntExpr xor +IntExpr
Bitwise `exclusive or' IntExpr1 and IntExpr2.
[ISO]\ +IntExpr
Bitwise negation. The returned value is the one's complement of IntExpr.
[ISO]sqrt(+Expr)
Result = sqrt(Expr)
[ISO]sin(+Expr)
Result = sin(Expr). Expr is the angle in radians.
[ISO]cos(+Expr)
Result = cos(Expr). Expr is the angle in radians.
tan(+Expr)
Result = tan(Expr). Expr is the angle in radians.
asin(+Expr)
Result = arcsin(Expr). Result is the angle in radians.
acos(+Expr)
Result = arccos(Expr). Result is the angle in radians.
[ISO]atan(+Expr)
Result = arctan(Expr). Result is the angle in radians.
atan(+YExpr, +XExpr)
Result = arctan(YExpr/XExpr). Result is the angle in radians. The return value is in the range [- pi ... pi ]. Used to convert between rectangular and polar coordinate system.
[ISO]log(+Expr)
Natural logarithm. Result = ln(Expr)
log10(+Expr)
Base-10 logarithm. Result = log10(Expr)
[ISO]exp(+Expr)
Result = e **Expr
[ISO]+Expr1 ** +Expr2
Result = Expr1**Expr2. With unbounded integers and integer values for Expr1 and a non-negative integer Expr2, the result is always integer. The integer expressions 0 ** I, 1 ** I and -1 ** I are guaranteed to work for any integer I. Other integer base values generate a `resource` error if the result does not fit in memory.
powm(+IntExprBase, +IntExprExp, +IntExprMod)
Result = (IntExprBase**IntExprExp) modulo IntExprMod. Only available when compiled with unbounded integer support. This formula is required for Diffie-Hellman key-exchange, a technique where two parties can establish a secret key over a public network.
+Expr1 ^ +Expr2
Same as **/2. (backward compatibility).
pi
Evaluates to the mathematical constant pi (3.14159 ... ).
e
Evaluates to the mathematical constant e (2.71828 ... ).
cputime
Evaluates to a floating point number expressing the CPU time (in seconds) used by Prolog up till now. See also statistics/2 and time/1.
eval(+Expr)
Evaluate Expr. Although ISO standard dictates that A=1+2, B is A works and unifies B to 3, it is widely felt that source-level variables in arithmetic expressions should have been limited to numbers. In this view the eval function can be used to evaluate arbitrary expressions.54The eval/1 function was first introduced by ECLiPSe and is under consideration for YAP.

Bitvector functions

The functions below are not covered by the standard. The msb/1 function is compatible to hProlog. The others are private extensions that improve handling of ---unbounded--- integers as bit-vectors.

msb(+IntExpr)
Return the largest integer N such that `(IntExpr >> N) /\ 1 =:= 1`. This is the (zero-origin) index of the most significant 1 bit in the value of IntExpr, which must evaluate to a positive integer. Errors for 0, negative integers, and non-integers.
lsb(+IntExpr)
Return the smallest integer N such that `(IntExpr >> N) /\ 1 =:= 1`. This is the (zero-origin) index of the least significant 1 bit in the value of IntExpr, which must evaluate to a positive integer. Errors for 0, negative integers, and non-integers.
popcount(+IntExpr)
Return the number of 1s in the binary representation of the non-negative integer IntExpr.