Trunc

From Free Pascal wiki
Jump to navigationJump to search

English (en) suomi (fi) русский (ru)

The Standard Pascal function trunc returns the integer part of a real-type value rounded toward zero.

trunc.png

trunc is short for “truncate”. The fraction part of the real value is, so to speak, cut off. However, unlike the int function the result is of integer type.

FPC implements this function as a compiler function.

definition

The mathematical definition reads as follows:

[math]\displaystyle{ \text{trunc}(x) := \begin{cases} \lfloor x \rfloor & \text{if } x \geq 0 \\ \lceil x \rceil & \text{if } x \lt 0 \end{cases} }[/math]

The function trunc is defined for all real values in the open interval (low(integer)-1high(integer)+1). If the supplied parameter is out of range, a program compiled with FPC will stop with the run-time error 207 “Invalid floating point operation”. If the sysUtils is included, this RTE becomes the eInvalidOp exception.

application

Trunc is used to retrieve an integer value. It is primarily used where no loss in accuracy is expected if the fractional part (if any) is removed.

For example: Pascal does not have a power operator or function built in. Instead, one has to define their own function doing this task using already existing function. One can utilize the rule [math]\displaystyle{ a^x = e^{x \times \ln a} }[/math] and the pre-existing exp and ln functions for that. However, if the operands are integers, it is guaranteed the result will be an integer to, yet exp will return a real value. The result can be truncated, without loss in precision. For source code, see asterisk § “exponentiation”.

see also