# 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.

Web page: https://pseudolearn.app/en/spec/biblioteca/matematicas

> **In one sentence**
>
> 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.

## 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 |

**Figure 12.4-1: Rounding -2.5**

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.

The four ways of taking -2.5 to an integer on the number line.

### Program: Functions and rounding

```pseudolearn
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**

```text
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.*

> **Limit**
>
> - An argument outside the domain —the root of a negative, the logarithm of zero— produces `nonFiniteRealResult`.
> - Rounding returns 64-bit integers: a real that is too large produces `integerOverflow`.

> **Common mistakes**
>
> ### Program: The root of a negative
>
> ```pseudolearn
> Algorithm Raiz
>   Write sqrt(-1);
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `nonFiniteRealResult` (error, 2:9): The operation produces a non-finite real value
>
> *The program finishes with an error.*

**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.

**See also**
- [4.3 Power](https://pseudolearn.app/en/spec/expresiones/potencia.md)
- [4.2 Division, Div and Mod](https://pseudolearn.app/en/spec/expresiones/division.md)
