EMZETT.
Login

Mathematical Functions

In short: Predefined functions for common mathematical operations (square root, power, rounding, random numbers, trigonometric functions, etc.), which almost every language ships with in a standard library.

In more detail: Instead of implementing basic operations like square root or rounding themselves, programs rely on a bundled library (in Java, for example, the Math class with Math.sqrt(), Math.pow(), Math.round()). This not only saves time, but also uses numerically tested, performant implementations instead of custom, potentially error-prone calculations.

In Depth

Typical functions that practically every standard library ships with:

sqrt(16)        -> 4
power(2, 10)      -> 1024
round(3.7)        -> 4
floor(3.7)       -> 3
ceil(3.2)      -> 4
abs(-5)     -> 5
min(3, 7)      -> 3
max(3, 7)      -> 7
random(1, 6)   -> random number between 1 and 6 (e.g. for a die)

A common pitfall is the various rounding functions: “round” (to the nearest integer value, 0.5 gets rounded up or down depending on the language — “round to even” vs. “always round up from .5”), “floor” (always to the next-smaller integer), and “ceiling” (always to the next-larger one) also often give surprising results for negative numbers (ceil(-3.2) gives -3, not -4) — when in doubt, check the specific documentation of the language in question instead of guessing.

Important for floating-point numbers (double/float): mathematical functions like sqrt() can return intermediate results that aren’t exactly representable (e.g. sqrt(2) is mathematically irrational, but technically only storable with limited precision) — a direct equality comparison (==) on the result of such a calculation is therefore risky; instead, you usually check whether the difference is smaller than a very small tolerance.

Random number functions deserve special attention: the “normal” random() function of most standard libraries is sufficient for games, simulations, or UI effects, but is NOT cryptographically secure — for security-relevant purposes (e.g. password tokens, session IDs), a dedicated cryptographically secure random function is needed instead.

See also: double, Type Casting