ceil, floor, round, trunc
--
rounding to an integerceil
rounds a number to the next larger integer.
floor
rounds a number to the next smaller integer.
round
rounds a number to the nearest integer.
trunc
rounds a number to the next integer in the
direction of 0.
ceil(x)
floor(x)
round(x)
trunc(x)
x |
- | an arithmetical expression |
an arithmetical expression.
x
The functions are sensitive to the environment variable DIGITS
which determines the
numerical working precision.
x
as a floating point number, then
trunc(x)
truncates the digits after the decimal point.
Thus, trunc
coincides with floor
for real
positive arguments and with ceil
for real negative
arguments, respectively.If the argument is a floating point number of absolute value larger than 10^DIGITS, the resulting integer is affected by internal non-significant digits! Cf. example 2.
Internally, exact numerical expressions that are
neither integers nor rational numbers are approximated by floating
point numbers before rounding. Thus, the resulting integer may depend
on the present value of DIGITS
! Cf. example 3.
We demonstrate the rounding of real and complex numbers:
>> ceil(3.5), floor(3.5), round(3.5), trunc(3.5)
4, 3, 4, 3
>> ceil(-7/2), floor(-7/2), round(-7/2), trunc(-7/2)
-3, -4, -3, -3
>> ceil(3 + 5/2*I), floor(4.3 + 7*I), round(I/2), trunc(I/2)
3 + 3 I, 4 + 7 I, I, 0
Also symbolic expressions representing numbers can be rounded:
>> x := PI*I + 7*sin(exp(2)): ceil(x), floor(x), round(x), trunc(x)
7 + 4 I, 6 + 3 I, 6 + 3 I, 6 + 3 I
Rounding of expressions with symbolic identifiers produces unevaluated function calls:
>> delete x: ceil(x), floor(x - 1), round(x + 1), trunc(x^2 + 3)
2 ceil(x), floor(x - 1), round(x + 1), trunc(x + 3)
Care should be taken when rounding floating point numbers of large absolute value:
>> x := 10^30/3.0
3.333333333e29
Note that only the first 10 decimal digits are ``significant''. Further digits are subject to round-off effects caused by the internal binary representation. These ``insignificant'' digits are part of the integer produced by rounding:
>> floor(x), ceil(x)
333333333333333333307205615616, 333333333333333333307205615616
>> delete x:
Exact numerical expressions are internally converted to
floating point numbers before rounding. Consequently, the present
setting of DIGITS
can
affect the result:
>> x := 10^30 - exp(30)^ln(10)
ln(10) 1000000000000000000000000000000 - exp(30)
Note that the exact value of this number is 0. Floating point evaluation is subject to severe cancellations:
>> DIGITS := 10: float(x), floor(x), ceil(x)
1.030792151e13, 10307921510400, 10307921510400
The floating point result is more accurate when a higher precision is used. The rounded values change accordingly:
>> DIGITS := 20: float(x), floor(x), ceil(x)
2896.0, 2896, 2896
>> DIGITS := 30: float(x), floor(x), ceil(x)
0.00000087916851043701171875, 0, 1
>> delete x, DIGITS: