math

Constants and math helpers inspired by C's math.h, implemented in pure Bern.

import math
Note: The transcendental functions (exp, log, sin, …) are computed with truncated series and iterative methods, so they are accurate approximations rather than bit-exact hardware results.

Constants

  • pi = 3.141592653589793
  • tau = 6.283185307179586 (2Ο€)
  • e = 2.718281828459045
2 * pi
-- Output: 6.283185307179586

Basic operations

abs(x) β†’ number

Absolute value; preserves the input's numeric type.

abs(-7)
-- Output: 7
fabs(x) β†’ number

Alias for abs that mirrors C's fabs.

fabs(-3.5)
-- Output: 3.5
fmin(a, b) β†’ double

The smaller of two numbers, computed in double space.

fmin(3, 8)
-- Output: 3.0
fmax(a, b) β†’ double

The larger of two numbers.

fmax(3, 8)
-- Output: 8.0
clamp(x, lo, hi) β†’ number

Constrain x to the interval [lo, hi].

clamp(15, 0, 10)
-- Output: 10.0
clamp(-2, 0, 10)
-- Output: 0.0
fmod(x, y) β†’ number

Floating-point remainder (C's fmod).

fmod(10, 3)
-- Output: 1

Powers & roots

pow(base, exponent) β†’ number

Raise base to an integer exponent by squaring. Negative exponents give reciprocals.

pow(2, 8)
-- Output: 256
pow(2, -1)
-- Output: 0.5
sqrt(x) β†’ double

Square root via Newton–Raphson iteration. Negative inputs return NaN.

sqrt(16)
-- Output: 4.0
hypot(a, b) β†’ double

The hypotenuse length √(a² + b²).

hypot(3, 4)
-- Output: 5.0

Exponential & logarithmic

exp(x) β†’ double

e raised to the power x (Taylor series).

exp(1)
-- Output: ~2.718281828
log(x) β†’ double

Natural logarithm (base e). Non-positive inputs return NaN.

log(e)
-- Output: ~1.0
log10(x) β†’ double

Base-10 logarithm.

log10(1000)
-- Output: ~3.0

Trigonometry

All trig functions take and return radians.

sin(radians) β†’ double

Sine of an angle.

sin(pi / 2)
-- Output: ~1.0
cos(radians) β†’ double

Cosine of an angle.

cos(0)
-- Output: 1.0
tan(radians) β†’ double

Tangent; NaN at odd multiples of Ο€/2.

tan(pi / 4)
-- Output: ~1.0
atan(z) β†’ double

Inverse tangent.

atan(1)
-- Output: ~0.785   (Ο€/4)
atan2(y, x) β†’ double

Two-argument arctangent that respects the quadrant of (x, y).

atan2(1, 1)
-- Output: ~0.785   (Ο€/4)

Angle conversion

toRadians(degrees) β†’ double

Convert degrees to radians.

toRadians(180)
-- Output: ~3.14159
toDegrees(radians) β†’ double

Convert radians to degrees.

toDegrees(pi)
-- Output: ~180.0

Putting it together

Several functions cooperate when you compute geometry. Here is the distance between two points, plus the angle of the line between them in degrees:

Distance and bearing between two points

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:

Capped quadratic growth

import math

def grow(level) -> clamp(pow(level, 2), 0, 100)

grow(5)
-- Output: 25.0
grow(12)
-- Output: 100.0   (144 clamped down)