- Documentation
- Reference manual
- Built-in Predicates
- Arithmetic
- General purpose arithmetic
- >/2
- </2
- =</2
- >=/2
- =\=/2
- =:=/2
- is/2
- Arithmetic types
- Rational number examples
- Arithmetic Functions
- -/1
- +/1
- +/2
- -/2
- */2
- f-//2
- mod/2
- rem/2
- f-///2
- div/2
- rdiv/2
- gcd/2
- abs/1
- sign/1
- copysign/2
- max/2
- min/2
- ./2
- random/1
- random_float/0
- round/1
- integer/1
- float/1
- rational/1
- rationalize/1
- float_fractional_part/1
- float_integer_part/1
- truncate/1
- floor/1
- ceiling/1
- ceil/1
- >>/2
- <</2
- f-\//2
- /\/2
- xor/2
- \/1
- sqrt/1
- sin/1
- cos/1
- tan/1
- asin/1
- acos/1
- atan/1
- atan2/2
- atan/2
- sinh/1
- cosh/1
- tanh/1
- asinh/1
- acosh/1
- atanh/1
- log/1
- log10/1
- exp/1
- **/2
- ^/2
- powm/3
- lgamma/1
- erf/1
- erfc/1
- pi/0
- e/0
- epsilon/0
- inf/0
- nan/0
- cputime/0
- eval/1
- msb/1
- lsb/1
- popcount/1
- getbit/2
- General purpose arithmetic
- Arithmetic
- Built-in Predicates
- Packages
- Reference manual
4.27.2.3 Arithmetic Functions
Arithmetic functions are terms which are evaluated by the arithmetic predicates described in section 4.27.2. 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 to an integer. |
RatExpr | Arbitrary expression that must evaluate to a rational number. |
FloatExpr | Arbitrary expression that must evaluate to a floating point. |
For systems using bounded integer arithmetic (default is unbounded, see section 4.27.2.1 for details), integer operations that would cause overflow automatically convert to floating point arithmetic.
SWI-Prolog provides many extensions to the set of floating point functions defined by the ISO standard. The current policy is to provide such functions on `as-needed' basis if the function is widely supported elsewhere and notably if it is part of the http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdfC99 mathematical library. In addition, we try to maintain compatibility with http://www.dcc.fc.up.pt/ vsc/Yap/YAP.
- [ISO]- +Expr
- Result = -Expr
- [ISO]+ +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. If 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, defined as 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, defined as Result is rnd_I(Expr1/Expr2)
. The function rnd_I is the default rounding used by the C
compiler and available through the Prolog flag
integer_rounding_function.
In the C99 standard, C-rounding is defined as
towards_zero
.108Future versions might guarantee rounding towards zero. - [ISO]div(+IntExpr1, +IntExpr2)
- Integer division, defined as Result is (IntExpr1 - IntExpr1 mod IntExpr2)
// IntExpr2. In other words, this is integer division that
rounds towards -infinity. This function guarantees behaviour that is
consistent with
mod/2, i.e., the
following holds for every pair of integers
X,Y where
Y =\= 0
.Q is div(X, Y), M is mod(X, Y), X =:= Y*Q+M.
- +RatExpr rdiv +RatExpr
- Rational number division. This function is only available if SWI-Prolog has been compiled with rational number support. See section 4.27.2.2 for details.
- +IntExpr1 gcd +IntExpr2
- Result is the greatest common divisor of IntExpr1, IntExpr2.
- [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. If Expr evaluates to a float, the return value is a float (e.g., -1.0, 0.0 or 1.0). In particular, note that sign(-0.0) evaluates to 0.0. See also copysign/2
- [ISO]copysign(+Expr1, +Expr2)
- Evaluate to X, where the absolute value of X equals the absolute value of Expr1 and the sign of X matches the sign of Expr2. This function is based on copysign() from C99, which works on double precision floats and deals with handling the sign of special floating point values such as -0.0. Our implementation follows C99 if both arguments are floats. Otherwise, copysign/2 evaluates to Expr1 if the sign of both expressions matches or -Expr1 if the signs do not match. Here, we use the extended notion of signs for floating point numbers, where the sign of -0.0 and other special floats is negative.
- [ISO]max(+Expr1, +Expr2)
- Evaluate to the larger of 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.
- [ISO]min(+Expr1, +Expr2)
- Evaluate to the smaller of 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) using the traditional mapping of double quoted string to a list of character codes. Arithmetic evaluation also translates a string object (see section 5.2) of one character length into the character code for that character. This implies that expression"a"
also works of the Prolog flag double_quotes is set tostring
. The recommended way to specify the character code of the letter `a' is0'a
. - random(+IntExpr)
- Evaluate to a random integer i for which 0 =< i < IntExpr.
The system has two implementations. If it is compiled with support for
unbounded arithmetic (default) it uses the GMP library random functions.
In this case, each thread keeps its own random state. The default
algorithm is the Mersenne Twister algorithm. The seed is set
when the first random number in a thread is generated. If available, it
is set from
/dev/random
.109On Windows the state is initialised from CryptGenRandom(). Otherwise it is set from the system clock. If unbounded arithmetic is not supported, random numbers are shared between threads and the seed is initialised from the clock when SWI-Prolog was started. The predicate set_random/1 can be used to control the random number generator.Warning! Although properly seeded (if supported on the OS), the Mersenne Twister algorithm does not produce cryptographically secure random numbers. To generate cryptographically secure random numbers, use crypto_n_random_bytes/2 from library
library(crypto)
provided by thessl
package. - random_float
- Evaluate to a random float I for which 0.0 < i < 1.0. This function shares the random state with random/1. All remarks with the function random/1 also apply for random_float/0. Note that both sides of the domain are open. This avoids evaluation errors on, e.g., log/1 or //2 while no practical application can expect 0.0.110Richard O'Keefe said: ``If you are generating IEEE doubles with the claimed uniformity, then 0 has a 1 in 2^53 = 1 in 9,007,199,254,740,992 chance of turning up. No program that expects [0.0,1.0) is going to be surprised when 0.0 fails to turn up in a few millions of millions of trials, now is it? But a program that expects (0.0,1.0) could be devastated if 0.0 did turn up.''
- [ISO]round(+Expr)
- Evaluate Expr and round the result to the nearest integer.
According to ISO, round/1
is defined as
floor(Expr+1/2)
, i.e., rounding down. This is an unconventional choice and under which the relationround(Expr) == -round(-Expr)
does not hold. SWI-Prolog rounds outward, e.g.,round(1.5) =:= 2
and roundround(-1.5) =:= -2
. - 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.27.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.111The
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 asceil(Expr)
. That is, truncate/1 rounds towards zero. - [ISO]floor(+Expr)
- Evaluate Expr and return the largest integer smaller or equal to the result of the evaluation.
- [ISO]ceiling(+Expr)
- Evaluate Expr and return the smallest integer larger or equal to the result of the evaluation.
- ceil(+Expr)
- Same as ceiling/1 (backward compatibility).
- [ISO]+IntExpr1 >> +IntExpr2
- 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 bits.
- [ISO]+IntExpr1 << +IntExpr2
- Bitwise shift IntExpr1 by IntExpr2 bits to the left.
- [ISO]+IntExpr1 \/ +IntExpr2
- Bitwise `or' IntExpr1 and IntExpr2.
- [ISO]+IntExpr1 /\ +IntExpr2
- Bitwise `and' IntExpr1 and IntExpr2.
- [ISO]+IntExpr1 xor +IntExpr2
- 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.
- [ISO]tan(+Expr)
- Result = tan(Expr). Expr is the angle in radians.
- [ISO]asin(+Expr)
- Result = arcsin(Expr). Result is the angle in radians.
- [ISO]acos(+Expr)
- Result = arccos(Expr). Result is the angle in radians.
- [ISO]atan(+Expr)
- Result = arctan(Expr). Result is the angle in radians.
- [ISO]atan2(+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.
Note that the ISO Prolog standard demands
atan2(0.0,0.0)
to raise an evaluation error, whereas the C99 and POSIX standards demand this to evaluate to 0.0. SWI-Prolog follows C99 and POSIX. - atan(+YExpr, +XExpr)
- Same as atan2/2 (backward compatibility).
- sinh(+Expr)
- Result = sinh(Expr). The hyperbolic sine of X is defined as e ** X - e ** -X / 2.
- cosh(+Expr)
- Result = cosh(Expr). The hyperbolic cosine of X is defined as e ** X + e ** -X / 2.
- tanh(+Expr)
- Result = tanh(Expr). The hyperbolic tangent of X is defined as sinh( X ) / cosh( X ).
- asinh(+Expr)
- Result = arcsinh(Expr) (inverse hyperbolic sine).
- acosh(+Expr)
- Result = arccosh(Expr) (inverse hyperbolic cosine).
- atanh(+Expr)
- Result = arctanh(Expr). (inverse hyperbolic tangent).
- [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. The
result is a float, unless SWI-Prolog is compiled with unbounded integer
support and the inputs are integers and produce an integer result. 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.The ISO standard demands a float result for all inputs and introduces ^/2 for integer exponentiation. The function float/1 can be used on one or both arguments to force a floating point result. Note that casting the input result in a floating point computation, while casting the output performs integer exponentiation followed by a conversion to float.
- [ISO]+Expr1 ^ +Expr2
- In SWI-Prolog, ^/2 is
equivalent to **/2. The
ISO version is similar, except that it produces a evaluation error if
both
Expr1 and Expr2 are integers and the result is not
an integer. The table below illustrates the behaviour of the
exponentiation functions in ISO and SWI.
Expr1 Expr2 Function SWI ISO Int Int **/2 Int or Float Float Int Float **/2 Float Float Rational Int **/2 Rational - Float Int **/2 Float Float Float Float **/2 Float Float Int Int ^/2 Int or Float Int or error Int Float ^/2 Float Float Rational Int ^/2 Rational - Float Int ^/2 Float Float Float Float ^/2 Float Float - 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. IntExprBase and IntExprExp must be non-negative (>=0), IntExprMod must be positive (>0).112The underlying GMP mpz_powm() function allows negative values under some conditions. As the conditions are expensive to pre-compute, error handling from GMP is non-trivial and negative values are not needed for Diffie-Hellman key-exchange we do not support these.
- lgamma(+Expr)
- Return the natural logarithm of the absolute value of the Gamma function.113Some interfaces also provide the sign of the Gamma function. We canot do that in an arithmetic function. Future versions may provide a predicate lgamma/3 that returns both the value and the sign.
- erf(+Expr)
- https://en.wikipedia.org/wiki/Error_functionWikipedia: ``In mathematics, the error function (also called the Gauss error function) is a special function (non-elementary) of sigmoid shape which occurs in probability, statistics and partial differential equations.''
- erfc(+Expr)
- https://en.wikipedia.org/wiki/Error_functionWikipedia: ``The complementary error function.''
- [ISO]pi
- Evaluate to the mathematical constant pi (3.14159 ... ).
- e
- Evaluate to the mathematical constant e (2.71828 ... ).
- epsilon
- Evaluate to the difference between the float 1.0 and the first larger floating point number.
- inf
- Evaluate to positive infinity. See section 2.16.1.6. This value can be negated using -/1.
- nan
- Evaluate to Not a Number. See section 2.16.1.6.
- cputime
- Evaluate 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.114The 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 also
appears in hProlog and SICStus Prolog. The getbit/2
function also appears in ECLiPSe, which also provides setbit(Vector,Index)
and clrbit(Vector,Index)
. The others are SWI-Prolog
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.
- getbit(+IntExprV, +IntExprI)
- Evaluates to the bit value (0 or 1) of the IntExprI-th bit of
IntExprV. Both arguments must evaluate to non-negative
integers. The result is equivalent to
(IntExprV >> IntExprI)/\1
, but more efficient because materialization of the shifted value is avoided. Future versions will optimise(IntExprV >> IntExprI)/\1
to a call to getbit/2, providing both portability and performance.115This issue was fiercely debated at the ISO standard mailinglist. The name getbit was selected for compatibility with ECLiPSe, the only system providing this support. Richard O'Keefe disliked the name and argued that efficient handling of the above implementation is the best choice for this functionality.