Logiweb(TM)

7.5.2 Arithmetic operations

Prev Up Next Page 187 of 800 Search internet


The usual arithmetic operations of addition, subtraction, and multiplication are as follows:

""D 8
+ x
- x
""D 10
x * y
""D 12
x + y
x - y

The ""D lines indicate the charges of the operators. So addition and subtraction has greatest charge, then comes multiplication, and then comes unary plus and minus. The charges are even so the constructs are pre-associative. As an example,

2 - 3 - 4

means

( 2 - 3 ) - 4

and

2 * 3 + 4 * 5

means

( 2 * 3 ) + ( 4 * 5 )

Division operations have charge 16:

""D 16
x div y
x mod y

As an example,

12 + 13 div 10

means

( 12 + 13 ) div 10

If x and y are integers and if y is positive, then x div y and x mod y denote the unique integers which satisfy the following:

x = ( x div y ) * y + ( x mod y )

0 <= x mod y < y

When y is zero or negative, x div y and x mod y return exception.

Note in particular that x div y and x mod y do not allow to divide by negative numbers (or, rather, throw an exception if someone tries to divide by a negative number). That is because there is no definition of division by negative numbers (or, rather, there are two possible ones which are equally good). The base page implements the most conservative solution to that which is to stick to the definition above which requires

0 <= x mod y < y

That condition cannot be satisfied when y is zero or negative. Anyone who wants to divide by negative numbers can define their own x div y and x mod y operations according to their preferences.

The floor ( x , y ) operation computes both x div y and x mod y and return them as a pair:

floor ( x , y ) == ( x div y ) :: ( x mod y )

The base page defines a total of four division operations which return a pair of a quotient and a remainder:

floor ( x , y )
ceiling ( x , y )
truncate ( x , y )
round ( x , y )

They all satisfy similar equations:

x = floor ( x , y ) head * y + floor ( x , y ) tail

x = ceiling ( x , y ) head * y + ceiling ( x , y ) tail

x = truncate ( x , y ) head * y + truncate ( x , y ) tail

x = round ( x , y ) head * y + round ( x , y ) tail

The difference is in the rounding direction. The floor, ceiling, truncate, and round operations round in the direction of minus infinity, plus infinity, zero, and nearest integer, respectively. For the latter, if two integers are equally near to the exact result, the even of the two is chosen. These four kinds of rounding correspond to the four rounding modes of the IEEE floating point standard.

Prev Up Next Page 187 of 800 Search logiweb.eu

Copyright © 2010 Klaus Grue, GRD-2010-01-05