In what follows are the implementations of several math functions.
\(\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
\(\text{sgn}(x)\) denotes the sign of \(x\)
def sgn(x):
if x < 0:
return -1
if x > 0:
return 1
return 0
\(H(x)\) denotes the Heaviside step of \(x\)
def H(x):
if x < 0:
return 0
if x > 0:
return 1
return 0.5
\(\lvert x \rvert\) denotes the absolute value of \(x\)
def abs(x):
if x < 0:
return -x
return x
\(\text{trunc}(x)\) denotes the truncation of \(x\), which is \(x\) without its non-integer part.
def trunc(x):
return int(x)
\(\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
\(\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
\(\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