Constants and math helpers inspired by C's math.h, implemented in pure Bern.
import math
exp, log, sin, β¦) are computed with truncated series and iterative methods, so they are accurate approximations rather than bit-exact hardware results.
pi = 3.141592653589793tau = 6.283185307179586 (2Ο)e = 2.7182818284590452 * pi -- Output: 6.283185307179586
Absolute value; preserves the input's numeric type.
abs(-7) -- Output: 7
Alias for abs that mirrors C's fabs.
fabs(-3.5) -- Output: 3.5
The smaller of two numbers, computed in double space.
fmin(3, 8) -- Output: 3.0
The larger of two numbers.
fmax(3, 8) -- Output: 8.0
Constrain x to the interval [lo, hi].
clamp(15, 0, 10) -- Output: 10.0 clamp(-2, 0, 10) -- Output: 0.0
Floating-point remainder (C's fmod).
fmod(10, 3) -- Output: 1
Raise base to an integer exponent by squaring. Negative exponents give reciprocals.
pow(2, 8) -- Output: 256 pow(2, -1) -- Output: 0.5
Square root via NewtonβRaphson iteration. Negative inputs return NaN.
sqrt(16) -- Output: 4.0
The hypotenuse length β(aΒ² + bΒ²).
hypot(3, 4) -- Output: 5.0
e raised to the power x (Taylor series).
exp(1) -- Output: ~2.718281828
Natural logarithm (base e). Non-positive inputs return NaN.
log(e) -- Output: ~1.0
Base-10 logarithm.
log10(1000) -- Output: ~3.0
All trig functions take and return radians.
Sine of an angle.
sin(pi / 2) -- Output: ~1.0
Cosine of an angle.
cos(0) -- Output: 1.0
Tangent; NaN at odd multiples of Ο/2.
tan(pi / 4) -- Output: ~1.0
Inverse tangent.
atan(1) -- Output: ~0.785 (Ο/4)
Two-argument arctangent that respects the quadrant of (x, y).
atan2(1, 1) -- Output: ~0.785 (Ο/4)
Convert degrees to radians.
toRadians(180) -- Output: ~3.14159
Convert radians to degrees.
toDegrees(pi) -- Output: ~180.0
Several functions cooperate when you compute geometry. Here is the distance between two points, plus the angle of the line between them in degrees:
import math x1 = 0.0 y1 = 0.0 x2 = 3.0 y2 = 3.0 dx = x2 - x1 dy = y2 - y1 distance = hypot(dx, dy) -- Output: ~4.2426 angle = toDegrees(atan2(dy, dx)) -- Output: ~45.0
And clamping with pow to build a simple "ease then cap" curve:
import math def grow(level) -> clamp(pow(level, 2), 0, 100) grow(5) -- Output: 25.0 grow(12) -- Output: 100.0 (144 clamped down)