Skip to content

SpecificationXII · Library

12.4

Mathematics and rounding

Mathematical functions compute roots, logarithms and trigonometry with results exact to the last bit, and rounding functions go from real to integer in four different ways.

Markdown version

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:

FunctionRule2.5-2.5
trunctowards zero2-2
roundto the nearest; ties away from zero3-3
floordownwards2-3
ceilupwards3-2
Figure 12.4-1.The four ways of taking -2.5 to an integer on the number line.

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);
EndAlgorithm

Output

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, floor and ceil go from real to integer.
  • Outside the domain, the program stops.