1% BEGIN LICENSE BLOCK 2% Version: CMPL 1.1 3% 4% The contents of this file are subject to the Cisco-style Mozilla Public 5% License Version 1.1 (the "License"); you may not use this file except 6% in compliance with the License. You may obtain a copy of the License 7% at www.eclipse-clp.org/license. 8% 9% Software distributed under the License is distributed on an "AS IS" 10% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See 11% the License for the specific language governing rights and limitations 12% under the License. 13% 14% The Original Code is The ECLiPSe Constraint Logic Programming System. 15% The Initial Developer of the Original Code is Cisco Systems, Inc. 16% Portions created by the Initial Developer are 17% Copyright (C) 1995 - 2006 Cisco Systems, Inc. All Rights Reserved. 18% 19% Contributor(s): 20% 21% END LICENSE BLOCK 22% 23% @(#)umsarith.tex 1.8 95/03/17 24% 25% 26% 27% REL DATE AUTHOR DESCRIPTION 28% 2.10 080489 David Miller Begin work on new arithmetic chapter 29% based on old builtins chapter. 30% 250489 Joachim Schimpf Modified for inline compiled arithmetic 31% 32\chapter{Arithmetic Evaluation\label{chaparith}} 33\index{arithmetic} 34%HEVEA\cutdef[1]{section} 35 36\section{Built-Ins to Evaluate Arithmetic Expressions} 37\index{arithmetic!built-ins}\index{built-ins!arithmetic} 38Unlike other languages, Prolog usually interprets an arithmetic expression like 39\notation{3 + 4} as a compound term with functor \notation{+} and two arguments. 40Therefore a query like \notation{3 + 4 = 7} fails because a compound term does 41not 42unify with a number. The evaluation of an arithmetic expression has to be 43explicitly requested by using one of the built-ins described below. 44 45\index{comparison!arithmetic}\index{arithmetic!comparison}% 46\index{arithmetic!built-ins!comparison}\index{built-ins!arithmetic!comparison} 47The basic predicate for evaluating an arithmetic expression is 48\bipref{is/2}{../bips/kernel/arithmetic/is-2.html}. 49Apart from that only the 6 arithmetic comparison predicates evaluate 50arithmetic expressions automatically. 51 52\begin{quote} 53\begin{description} 54\item[\pattern{Result} is \pattern{Expression}]\indextt{is/2} 55\about{Expression} is a valid arithmetic expression and \about{Result} 56is an uninstantiated variable or a number. 57The system evaluates \about{Expression} which yields a numeric result. 58This result is then unified with \about{Result}. 59An error occurs if \about{Expression} is not a valid arithmetic expression or 60if the evaluated value and \about{Result} are of different types. 61 62\item[\pattern{Expr1} $<$ \pattern{Expr2}]\indextt{</2} 63succeeds if (after evaluation and type coercion) \about{Expr1} is less than 64\about{Expr2}. 65 66\item[\pattern{Expr1} $>=$ \pattern{Expr2}]\indextt{>=/2} 67succeeds if (after evaluation and type coercion) \about{Expr1} is greater or 68equal to \about{Expr2}. 69 70\item[\pattern{Expr1} $>$ \pattern{Expr2}]\indextt{>/2} 71succeeds if (after evaluation and type coercion) \about{Expr1} is greater than 72\about{Expr2}. 73 74\item[\pattern{Expr1} $=<$ \pattern{Expr2}]\indextt{=</2} 75succeeds if (after evaluation and type coercion) \about{Expr1} is less or equal 76to \about{Expr2}. 77 78\item[\pattern{Expr1} =:= \pattern{Expr2}]\indextt{=:=/2} 79succeeds if (after evaluation and type coercion) \about{Expr1} is equal to 80\about{Expr2}. 81 82\item[\pattern{Expr1} =\bsl= \pattern{Expr2}]% 83\index{=\bsl=/2@\notation{=}\bsl\notation{=/2}} 84succeeds if (after evaluation and type coercion) \about{Expr1} is not equal to 85\about{Expr2}. 86\end{description} 87\end{quote} 88 89 90\subsection{Arithmetic Evaluation vs Arithmetic Constraint Solving} 91 92This chapter deals purely with the evaluation of arithmetic expressions 93containing numbers. No uninstantiated variables must occur within the 94expressions at the time they are evaluated. This is exactly like 95arithmetic evaluation in procedural languages. 96 97As opposed to that, in arithmetic constraint solving one can state 98equalities and inequalities involving variables, and a constraint 99solver tries to find values for these variables which satisfy these 100constraints. Note that {\eclipse} uses the same syntax in both cases, 101but different implementations providing different solving capabilities. 102See the chapter \chapname{Common Solver Interface} in the 103\ahref{../libman/libman.html}{Constraint Library Manual} for an overview. 104 105 106\section{Numeric Types and Type Conversions} 107\index{arithmetic!types}\index{types!arithmetic} 108{\eclipse} distinguishes four types of numbers: \defnotionni{integers}, 109\defnotionni{rationals}, \defnotionni{floats} and \defnotionni{bounded reals}. 110% we might have bounded integers at some point... 111 112\subsection{Integers\label{intrep}} 113\index{integers} 114\index{bignum} 115\index{type!integer} 116The magnitude of integers is only limited by your available 117memory. However, integers that fit into the word size of your computer are 118represented more efficiently (this distinction is invisible to the user). 119Integers are written in decimal notation or in base notation, for example: 120\begin{quote} 121\begin{verbatim} 1220 3 -5 1024 16'f3ae 0'a 15511210043330985984000000 123\end{verbatim} 124\end{quote} 125 126Note that integer range is unlimited if {\eclipse} was compiled with 127bignum support. Otherwise, integers are restricted to that representable 128in a machine word, and \notation{max_integer flag} of 129\bipref{get_flag/2}{../bips/kernel/env/get_flag-2.html} 130returns the maximum integer value. 131 132\subsection{Rationals} 133\index{rational numbers} 134\index{type!rational} 135Rational numbers implement the corresponding mathematical domain, 136i.e., ratios of two integers (numerator and denominator). 137{\eclipse} represents rationals in a canonical form where the 138greatest common divisor of numerator and denominator is 1 and the 139denominator is positive. Rational constants are written as numerator 140and denominator separated by an underscore, e.g., 141\begin{quote} 142\begin{verbatim} 1431_3 -30517578125_32768 0_1 144\end{verbatim} 145\end{quote} 146Rational arithmetic is arbitrarily precise. When the global flag 147\index{global flag!prefer_rationals} 148\notationidx{prefer_rationals} is set, the system uses rational arithmetic 149wherever possible. In particular, dividing two integers then yields a precise 150rational rather than a float result. 151 152Rationals are supported if {\eclipse} is compiled with bignum support. 153If rationals are not supported, a type error will be raised when a rational is 154required. 155 156\subsection{Floating Point Numbers} 157\index{floating point numbers} 158\index{type!float} 159Floating point numbers conceptually correspond to the mathematical 160domain of real numbers, but are not precisely represented. 161Floats are written with decimal point and/or an exponent, e.g., 162\begin{quote} 163\begin{verbatim} 1640.0 3.141592653589793 6.02e23 -35e-12 -1.0Inf 165\end{verbatim} 166\end{quote} 167{\eclipse} uses double precision floats\footnote{% 168 {\eclipse} versions older than 5.5 optionally supported single precision 169 floats. This is no longer the case.}. 170 171 172\subsection{Bounded Real Numbers} 173\index{bounded reals} 174\index{breal} 175\index{type!breal} 176It is a well known problem that floating point arithmetic suffers 177from rounding errors. 178To provide safe arithmetic over the real numbers, {\eclipse} 179also implements bounded reals\footnote{% 180 We have chosen to use the term \about{bounded real} rather than 181 \about{interval} in order to avoid confusion with interval variables 182 as used in the interval arithmetic constraint solvers}. 183A bounded real consists of a pair of floating point numbers 184which constitute a safe lower and upper bound for the real number that 185is being represented. Bounded reals are written as two floating point 186numbers separated by two underscores, e.g., 187\begin{quote} 188\begin{verbatim} 189-0.001__0.001 3.141592653__3.141592654 1e308__1.0Inf 190\end{verbatim} 191\end{quote} 192A bounded real is a representation for a real number that definitely lies 193somewhere between the two bounds, but the exact value cannot be determined\ 194\footnote{% 195 This is in contrast to a floating point number, which represents 196 a real number which lies somewhere in the vicinity of the float}. 197Bounded reals are usually not typed in by the user, they are normally 198the result of a computation or type coercion. 199 200All computations with bounded reals give safe results, taking rounding 201errors into account. This is achieved by doing \Index{interval arithmetic} 202on the bounds and rounding the results outwards. The resulting 203bounded real is then guaranteed to enclose the true real result. 204 205Computations with floating point values result in uncertainties 206about the correct result. Bounded reals make this uncertainty 207explicit. A consequence of this is that sometimes it is conceptually 208not possible to decide whether two bounded reals are identical or not. 209This occurs when the bounds of the compared intervals overlap. 210In this case, the arithmetic comparisons leave a (ground) delayed goal 211behind which can then be inspected by the user to decide whether the 212match is considered close enough. The syntactical comparisons like 213\txtbipref{=/2}{(=)/2}{../bips/kernel/termcomp/E-2.html} and 214\txtbipref{==/2}{(==)/2}{../bips/kernel/termcomp/EE-2.html} treat bounded reals 215simply as a pair of bounds, and consider them equal when the bounds are 216equal. 217 218 219\subsection{Type Conversions} 220Note that numbers of different types never unify, e.g., 3, 3_1, 3.0 221and 3.0__3.0 are all different. 222Use the arithmetic comparison predicates when you want to 223compare numeric values. 224When numbers of different types occur as arguments of an arithmetic 225operation or comparison, the types are first made equal by converting 226to the more general of the two types, i.e., the rightmost one in the sequence 227\begin{quote} 228integer $\rightarrow$ rational $\rightarrow$ float $\rightarrow$ bounded real 229\end{quote} 230The operation or comparison is then carried out with this type and the 231result is of this type as well, unless otherwise specified. 232Beware of the potential loss of precision in the 233rational $\rightarrow$ float conversion! 234Note that the system never does automatic conversions in the opposite direction. 235Such conversion must be programmed explicitly using the 236\biptxtref{integer}{integer/2}{../bips/kernel/arithmetic/integer-2.html}, 237\biptxtref{rational}{rational/2}{../bips/kernel/arithmetic/rational-2.html}, 238\biptxtref{float}{float/2}{../bips/kernel/arithmetic/float-2.html} and 239\biptxtref{breal}{breal/2}{../bips/kernel/arithmetic/breal-2.html} 240functions. 241 242\section{Arithmetic Functions} 243\index{arithmetic!functions}\index{functions!arithmetic} 244\subsection{Predefined Arithmetic Functions} 245\index{arithmetic!predefined arithmetic functions} 246The following predefined arithmetic functions are available. 247\about{E}, \about{E1} and \about{E2} stand for 248arbitrary arithmetic expressions. 249 250\vspace{2mm} 251\noindent 252{\small 253\begin{tabular}{l l l l} 254Function & Description & Argument Types & Result Type \\ 255\hline 256+ E & unary plus & number & number \\ 257-- E & unary minus & number & number \\ 258abs(E) & absolute value & number & number \\ 259sgn(E) & sign value & number & integer \\ 260floor(E) & round down to integral value & number & number \\ 261ceiling(E) & round up to integral value & number & number \\ 262round(E) & round to nearest integral value & number & number \\ 263truncate(E) & truncate to integral value & number & number \\ 264E1 + E2 & addition & number $\times$ number & number \\ 265E1 -- E2 & subtraction & number $\times$ number & number \\ 266E1 * E2 & multiplication & number $\times$ number & number \\ 267E1 / E2 & division & number $\times$ number & see below \\ 268E1 // E2 & integer division (truncate) & integer $\times$ integer & integer \\ 269E1 rem E2 & integer remainder & integer $\times$ integer & integer \\ 270E1 div E2 & integer division (floor) & integer $\times$ integer & integer \\ 271E1 mod E2 & integer modulus & integer $\times$ integer & integer \\ 272gcd(E1,E2) & greatest common divisor & integer $\times$ integer & integer \\ 273lcm(E1,E2) & least common multiple & integer $\times$ integer & integer \\ 274E1 \char`\^\ E2 & power operation & number $\times$ number & number \\ 275min(E1,E2) & minimum of 2 values & number $\times$ number & number \\ 276max(E1,E2) & maximum of 2 values & number $\times$ number & number \\ 277\verb:\: E & bitwise complement & integer & integer \\ 278E1 \verb:/\: E2 & bitwise conjunction & integer $\times$ integer & integer \\ 279E1 \verb:\/: E2 & bitwise disjunction & integer $\times$ integer & integer \\ 280xor(E1,E2) & bitwise exclusive disjunction & integer $\times$ integer & integer \\ 281E1 $>>$ E2 & shift E1 right by E2 bits & integer $\times$ integer & integer \\ 282E1 $<<$ E2 & shift E1 left by E2 bits & integer $\times$ integer & integer \\ 283sin(E) & trigonometric function & number & real \\ 284cos(E) & trigonometric function & number & real \\ 285tan(E) & trigonometric function & number & real \\ 286asin(E) & trigonometric function & number & real \\ 287acos(E) & trigonometric function & number & real \\ 288atan(E) & trigonometric function & number & real \\ 289atan(E1,E1) & trigonometric function & number $\times$ number & real \\ 290exp(E) & exponential function \( e^{x} \) & number & real \\ 291ln(E) & natural logarithm & number & real \\ 292sqrt(E) & square root & number & real \\ 293pi & the constant pi = 3.1415926... & --- & float \\ 294e & the constant e = 2.7182818... & --- & float \\ 295fix(E) & convert to integer (truncate) & number & integer \\ 296integer(E) & convert to integer (exact) & number & integer \\ 297float(E) & convert to float & number & float \\ 298breal(E) & convert to bounded real & number & breal \\ 299rational(E) & convert to rational & number & rational \\ 300rationalize(E) & convert to rational & number & rational \\ 301numerator(E) & extract numerator of a rational & integer or rational & 302 integer \\ 303denominator(E) & extract denominator of a rational & integer or rational & 304 integer \\ 305sum(L) & sum of list elements & list & number \\ 306min(L) & minimum of list elements & list & number \\ 307max(L) & maximum of list elements & list & number \\ 308eval(E) & evaluate runtime expression & term & number \\ 309\end{tabular} 310} 311\vspace{2mm} 312\vfill %<<<<<<<<<<< 313\pagebreak %<<<<<<<<<<< 314 315\noindent 316Argument types other than specified yield a type error. 317As an argument type, \about{number} stands for \about{integer}, 318\about{rational}, \about{float} or \about{breal} with the type conversions as 319specified above. 320As a result type, \about{number} stands for 321\emph{the more general of the argument types}, and \about{real} stands for 322\about{float} or \about{breal}. 323The division operator \notation{/} yields either a rational or a float result, 324depending on the value of the global flag 325\notationidx{prefer_rationals}.% 326\index{global flag!prefer_rationals}\index{arithmetic!prefer_rationals} 327The same is true for the result of \char`\^\ if an integer is raised to 328a negative integral power. 329 330The integer division \notation{//} rounds the result towards zero (truncates), 331while the \notation{div} division rounds towards negative infinity (floor). 332Each division function is paired with a corresponding remainder function: 333(\notation{rem} computes the remainder corresponding to \notation{//}, and 334\notation{mod} 335computes the remainder corresponding to \notation{div}\ 336\footnote{% 337 Caution: In {\eclipse} versions up to 5.8, \notation{mod} was the 338 remainder corresponding to \notation{//}, i.e., behaved like \notation{rem}}. 339The remainder results differ only in the case where the two arguments 340have opposite signs. The relationship between them is as follows: 341\begin{quote} 342\begin{verbatim} 343X =:= (X rem Y) + (X // Y) * Y 344X =:= (X mod Y) + (X div Y) * Y 345\end{verbatim} 346\end{quote} 347This table gives an overview: 348\begin{quote} 349\begin{verbatim} 350 10 x 3 -10 x 3 10 x -3 -10 x -3 351 352// 3 -3 -3 3 353rem 1 -1 1 -1 354div 3 -4 -4 3 355mod 1 2 -2 -1 356\end{verbatim} 357\end{quote} 358 359\subsection{Evaluation Mechanism} 360\index{arithmetic!expressions} 361 362An arithmetic expression is a Prolog term that is made up of variables, 363numbers, atoms and compound terms, e.g., 364\begin{quote} 365\begin{verbatim} 3663 * 1.5 + Y / sqrt(pi) 367\end{verbatim}\end{quote} 368Compound terms are evaluated by first evaluating their arguments and then 369calling the corresponding evaluation predicate. 370The evaluation predicate associated with a compound term 371 \notation{func(a_1,..,a_n)} 372is the predicate \predspec{func/}$(n+1)$. It receives 373\notation{a_1},..,\notation{a_n} as its first 374\about{n} arguments and returns a numeric result as its last argument. 375This result is then used in the arithmetic computation. 376For instance, the expression above would be evaluated by the goal sequence 377\begin{quote} 378\begin{verbatim} 379*(3,1.5,T1), sqrt(3.14159,T2), /(Y,T2,T3), +(T1,T3,T4) 380\end{verbatim}\end{quote} 381where \about{T1}, \about{T2} etc. are auxiliary variables created by the system 382to hold 383intermediate results. 384 385Although this evaluation mechanism is usually transparent to the user, it 386becomes visible when errors occur, when subgoals are delayed, or 387when inline-expanded code is traced. 388 389\subsection{User Defined Arithmetic Functions} 390\index{arithmetic!user defined arithmetic} 391This evaluation mechanism outlined above is not restricted to the 392predefined arithmetic functions shown in the table. 393In fact it works for all atoms and compound terms. 394It is therefore possible to define a new arithmetic operation by 395just defining an evaluating predicate: 396\index{factorial function} 397\begin{quote} 398\begin{verbatim} 399[eclipse 1]: [user]. 400 :- op(200, yf, !). % let's have some syntaxtic sugar 401 !(N, F) :- fac(N, 1, F). 402 fac(0, F0, F) :- !, F=F0. 403 fac(N, F0, F) :- N1 is N-1, F1 is F0*N, fac(N1, F1, F). 404 user compiled traceable 504 bytes in 0.00 seconds 405 406yes. 407[eclipse 2]: X is 23!. % calls !/2 408 409X = 25852016738884976640000 410yes. 411\end{verbatim} 412\end{quote} 413Note that this mechanism is not only useful for user-defined predicates, but 414can also be used to call {\eclipse} built-ins inside arithmetic expressions, 415e.g., 416\begin{quote} 417\begin{verbatim} 418T is cputime - T0. 419L is string_length("abcde") - 1. 420\end{verbatim}\end{quote} 421which call \bipref{cputime/1}{../bips/kernel/opsys/cputime-1.html} and 422\bipref{string_length/2}{../bips/kernel/stratom/string_length-2.html} 423respectively. 424Any predicate that returns a number as its last argument 425can be used in a similar manner. 426 427However there is a difference compared to the evaluation of the predefined 428arithmetic functions (as listed in the table above): 429The arguments of the user-defined arithmetic expression are \emph{not 430evaluated} but passed unchanged to the evaluating predicate. 431For example, the expression \notation{twice(3+4)} is transformed into the goal 432\notation{twice(3+4, Result)} rather than \notation{twice(7, Result)}. 433This makes sense because otherwise it would not be possible to pass 434any compound term to the predicate. 435If evaluation is wanted, the user-defined predicate can explicitly call 436\bipref{is/2}{../bips/kernel/arithmetic/is-2.html} or use \predspec{eval/1}. 437 438\subsection{Runtime Expressions} 439In order to enable efficient compilation of arithmetic expressions, 440{\eclipse} requires that variables in compiled arithmetic expressions 441must be bound to numbers at runtime, not symbolic expressions. 442For example, in the following code \predspec{p/1} will only work when called 443with a 444numerical argument, else it will raise error 24: 445\begin{quote} 446\begin{verbatim} 447p(Number) :- Res is 1 + Number, ... 448\end{verbatim} 449\end{quote} 450To make it work even when the argument gets bound to a symbolic expression 451at runtime, use \predspec{eval/1} as in the following example: 452\begin{quote} 453\begin{verbatim} 454p(Expr) :- Res is 1 + eval(Expr), ... 455\end{verbatim} 456\end{quote} 457If the expression is the only argument of \predspec{is/2}, the \predspec{eval/1} 458may be omitted. 459 460 461\section{Low Level Arithmetic Builtins} 462The low level builtins (like 463\txtbipref{+/3}{+/3}{../bips/kernel/arithmetic/P-3.html}, 464\bipref{sin/2}{../bips/kernel/arithmetic/sin-2.html} etc.) 465which are used to evaluate 466the predefined arithmetic functions can also be called directly, 467but this is not recommended for portability reasons. 468\index{compiler!arithmetic} 469Moreover, there is no need to use them directly since the {\eclipse} compiler 470will transform all arithmetic expressions into calls to the corresponding 471low level builtins. 472 473\section{The Multi-Directional Arithmetic Predicates}% 474A drawback of arithmetic using 475\bipref{is/2}{../bips/kernel/arithmetic/is-2.html} is that the right hand side 476must 477be fully instantiated at evaluation time. 478Often it is desirable to have predicates that define true logic 479relationships between their arguments like ``\about{Z} is the sum of \about{X} 480and \about{Y}''. 481For integer addition and multiplication this is provided as: 482\begin{quote} 483\begin{description} 484\item[succ(X, Y)]\indextt{succ/2} 485True if \about{X}and \about{Y} are natural numbers, and \about{Y} is one greater 486than \about{X}. 487At most one of \about{X}, \about{Y} can be a variable. 488 489\item[plus(X, Y, Z)]\indextt{plus/3} 490True if the sum of \about{X} and \about{Y} is \about{Z}. At most one of 491\about{X}, \about{Y}, \about{Z} can be a variable. 492 493\item[times(X, Y, Z)]\indextt{times/3} 494True if the product of \about{X} and \about{Y} is \about{Z}. At most one of 495\about{X}, \about{Y}, \about{Z} can be a variable. 496 497\end{description} 498\end{quote} 499 500These predicates work only with integer arguments but any single argument 501can be a variable which is then instantiated so that the relation holds. 502If more than one argument is uninstantiated, an instantiation fault is produced. 503 504Note that if one of the first two arguments is a variable, 505a solution doesn't necessarily exist. For example, the following goal has 506no integer solution : 507\begin{quote} 508\begin{verbatim} 509[eclipse 1]: times(2, X, 3). 510 511no (more) solution. 512\end{verbatim}\end{quote} 513 514Since any one of the arguments of these two predicates can be a variable, 515it does not make much sense to use them in arithmetic expressions 516where always the first arguments are taken as input and the last 517one as output. 518 519\section{Arithmetic and Coroutining} 520\index{arithmetic!coroutining} 521\index{coroutining!arithmetic} 522\index{delay!arithmetic} 523\label{arithdelay} 524 525Arithmetic comparisons can be delayed until their arguments are 526instantiated instead of generating an instantiation fault by passing the 527comparison to the suspend solver (see section~\ref{suspendsolver}). This 528gives a form of coroutining. 529 530%HEVEA\cutend 531 532