aiken/math
This module contains some basic Math utilities. Standard arithmetic operations on integers are available through native operators:
Operator | Description |
---|---|
+ | Arithmetic sum |
- | Arithmetic difference |
/ | Whole division |
* | Arithmetic multiplication |
% | Remainder by whole division |
Here are a few examples:
1 + 1 // 2
10 - 2 // 8
40 / 14 // 2
3 * 4 // 12
10 % 3 // 1
Functions
Calculate the absolute value of an integer.
math.abs(-42) == 42
math.abs(14) == 14
Restrict the value of an integer between two min and max bounds
math.clamp(14, min: 0, max: 10) == 10
The greatest common divisor of two integers.
math.gcd(42, 14) == 14
math.gcd(14, 42) == 14
math.gcd(0, 0) == 0
Checks if an integer has a given integer square root x. The check has constant time complexity O(1).
math.is_sqrt(0, 0)
math.is_sqrt(25, 5)
!math.is_sqrt(25, -5)
math.is_sqrt(44203, 210)
The logarithm in base b
of an element using integer divisions.
math.log(10, base: 2) == 3
math.log(42, base: 2) == 5
math.log(42, base: 3) == 3
math.log(5, base: 0) == 0
math.log(4, base: 4) == 1
math.log(4, base: 42) == 0
The integer logarithm in base 2. Faster than log
in this particular case.
math.log2(1) == 0
math.log2(2) == 1
math.log2(3) == 1
math.log2(4) == 2
math.log2(256) == 8
math.log2(257) == 8
math.log2(511) == 8
math.log2(1025) == 10
Calculates a number to the power of e
using the exponentiation by
squaring method.
math.pow(3, 5) == 243
math.pow(7, 2) == 49
math.pow(3, -4) == 0
math.pow(0, 0) == 1
math.pow(513, 3) == 135005697
Calculates the power of 2 for a given exponent e
. Much cheaper than
using pow(2, _)
for small exponents 0 < e < 256.
math.pow2(-2) == 0
math.pow2(0) == 1
math.pow2(1) == 2
math.pow2(4) == 16
math.pow2(42) == 4398046511104
Calculates the square root of an integer using the Babylonian method. This returns either the exact result or the smallest integer nearest to the square root.
Returns None
for negative values.
math.sqrt(0) == Some(0)
math.sqrt(25) == Some(5)
math.sqrt(44203) == Some(210)
math.sqrt(-42) == None
This function can be quite expensive to perform on-chain. Prefer using
is_sqrt
whenever possible.