Implementing Math Functions

In what follows are the implementations of several math functions.

Clamp

\(\text{clamp}(x, \text{mini}, \text{maxi})\) denotes \(x\) clamped to the interval \([\text{mini}, \text{maxi}]\)


def clamp(x, mini, maxi):
	if x < mini:
		return mini
	if x > maxi:
		return maxi
	return x

Sign

\(\text{sgn}(x)\) denotes the sign of \(x\)


def sgn(x):
	if x < 0:
		return -1
	if x > 0:
		return 1
	return 0

Heaviside Step

\(H(x)\) denotes the Heaviside step of \(x\)


def H(x):
	if x < 0:
		return 0
	if x > 0:
		return 1
	return 0.5
	

Absolute Value

\(\lvert x \rvert\) denotes the absolute value of \(x\)


def abs(x):
	if x < 0:
		return -x
	return x

Truncate

\(\text{trunc}(x)\) denotes the truncation of \(x\), which is \(x\) without its non-integer part.


def trunc(x):
	return int(x)

Floor

\(\lfloor x \rfloor\) denotes the floor of \(x\), which is the largest integer less than or equal to \(x\)


def floor(x):
	i = trunc(x)
	if x >= 0 or i == x:
		return i
	return i - 1

Ceiling

\(\lceil x \rceil\) denotes the ceiling of \(x\), which is the smallest integer greater than or equal to \(x\)


def ceil(x):
	i = trunc(x)
	if x <= 0 or i == x:
		return i
	return i + 1

Nearest Integer Function

\(\text{nint}(x)\) denotes the integer closest to \(x\). In the event of a tie, the even integer is chosen.


def nint(x):
	floor_x = floor(x)
	ceil_x = ceil(x)
	if x - floor_x < 0.5:
		return floor_x
	if ceil_x - x < 0.5:
		return ceil_x
	if floor_x % 2 == 0:
		return floor_x
	return ceil_x