bahaghari/lib: add math.mod' function

This commit is contained in:
Gabriel Arazas 2024-06-15 13:38:42 +08:00
parent 25654828c0
commit a170fd8344
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
2 changed files with 93 additions and 0 deletions

View File

@ -238,6 +238,44 @@ rec {
in
floor (difference + 0.5) * nearest;
/* Similar to the nixpkgs' `trivial.mod` but retain the decimal values. This
is just an approximation from ECMAScript's implementation of the modulo
operator (%).
Type: mod' :: Number -> Number -> Number
Example:
mod' 4.25 2
=> 0.25
mod' 1.5 2
=> 1.5
mod' 65 5
=> 0
mod' (-54) 4
=> -2
mod' (-54) (-4)
=> -2
*/
mod' = base: number:
let
base' = abs base;
number' = abs number;
difference = number' * ((floor base' / (floor number')) + 1);
result = number' - (difference - base');
in
if number' > base' then
base
else
if base < 0 then
-(result)
else
result;
/* Adds all of the given items on the list starting from a sum of zero.
Type: summate :: List[Number] -> Number

View File

@ -212,6 +212,61 @@ lib.runTests {
expected = 1.4142135624;
};
testMathMod = {
expr = self.math.mod' 65.5 3;
expected = 2.5;
};
testMathMod2 = {
expr = self.math.mod' 1.5 3;
expected = 1.5;
};
testMathMod3 = {
expr = self.math.mod' 4.25 2;
expected = 0.25;
};
testMathMod4 = {
expr = self.math.mod' 6 6;
expected = 0;
};
testMathMod5 = {
expr = self.math.mod' 6.5 6;
expected = 0.5;
};
testMathMod6 = {
expr = self.math.mod' 7856.5 20;
expected = 16.5;
};
testMathMod7 = {
expr = self.math.mod' 7568639.2 45633;
expected = 39194.200000000186;
};
testMathModBothPositive = {
expr = self.math.mod' 54.5 20.5;
expected = 13.5;
};
testMathModNegativeBase = {
expr = self.math.mod' (-54.5) 20.5;
expected = -13.5;
};
testMathModNegativeNumber = {
expr = self.math.mod' 54.5 (-20.5);
expected = 13.5;
};
testMathModBothNegatives = {
expr = self.math.mod' (-54.5) (-20.5);
expected = -13.5;
};
testMathExp = {
expr = self.math.exp 1;
expected = 2.7182818284590452353602874713527;