12.4.1 How it works
Mathematical functions accept integers or reals and return reals: sqrt, abs, ln, exp, log10, log2, and the trigonometry in radians sin, cos, tan, asin, acos, atan, atan2. min and max return an integer if both arguments are integers.
The result is always the real closest to the exact value, on any machine: it does not depend on the system's maths library.
To go from real to integer there are four functions, which only differ on numbers with decimals:
| Function | Rule | 2.5 | -2.5 |
|---|---|---|---|
trunc | towards zero | 2 | -2 |
round | to the nearest; ties away from zero | 3 | -3 |
floor | downwards | 2 | -3 |
ceil | upwards | 3 | -2 |
A line with -3, -2 and -1 and the point -2.5. floor and round take it to -3; ceil and trunc take it to -2.
ProgramFunctions and rounding
Algorithm Mates
Write sqrt(16), " ", abs(-3), " ", trunc(2.7), " ", round(2.5), " ", round(-2.5);
Write floor(-2.5), " ", ceil(-2.5), " ", min(3, 7), " ", max(2, 4.5);
Write ln(1), " ", exp(0), " ", sin(0), " ", cos(0), " ", log10(1000), " ", log2(8);
EndAlgorithmOutput
4.0 3.0 2 3 -3 -3 -2 3 4.5 0.0 1.0 0.0 1.0 3.0 3.0
The program finishes normally.
In short
- Mathematical functions return exact reals on any machine.
trunc,round,floorandceilgo from real to integer.- Outside the domain, the program stops.