bahaghari/lib: simplify math.remainder

Indeed I'm too dumb for mathematics. :p

Also, now the remainder implementation is double-checked with Python 3's
math.remainder() function.
This commit is contained in:
Gabriel Arazas 2024-06-15 19:45:33 +08:00
parent 4bd8aee223
commit 61720afeb2
No known key found for this signature in database
GPG Key ID: 62104B43D00AA360
2 changed files with 11 additions and 20 deletions

View File

@ -253,8 +253,8 @@ rec {
floor (difference + 0.5) * nearest; floor (difference + 0.5) * nearest;
/* Similar to the nixpkgs' `trivial.mod` but retain the decimal values. This /* Similar to the nixpkgs' `trivial.mod` but retain the decimal values. This
is just an approximation from ECMAScript's implementation of the modulo is just an approximation from ECMAScript's implementation of the remainder
operator (%) which is more like a remainder operator. operator.
Type: remainder :: Number -> Number -> Number Type: remainder :: Number -> Number -> Number
@ -274,20 +274,11 @@ rec {
remainder (-54) (-4) remainder (-54) (-4)
=> -2 => -2
*/ */
remainder = base: number: remainder = dividend: divisor:
let let
base' = abs base; quotient = dividend / divisor;
number' = abs number;
difference = number' * ((floor (base' / number')) + 1);
result = abs (number' - (difference - base'));
in in
if number' > base' dividend - ((floor quotient) * divisor);
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. /* Adds all of the given items on the list starting from a sum of zero.

View File

@ -268,22 +268,22 @@ lib.runTests {
expected = 0.5; expected = 0.5;
}; };
testMathRemainderBothPositive = { testMathRemainderPositiveOperands = {
expr = self.math.remainder 54.5 20.5; expr = self.math.remainder 54.5 20.5;
expected = 13.5; expected = 13.5;
}; };
testMathRemainderNegativeBase = { testMathRemainderNegativeDividend = {
expr = self.math.remainder (-54.5) 20.5; expr = self.math.remainder (-54.5) 20.5;
expected = -13.5; expected = 7;
}; };
testMathRemainderNegativeNumber = { testMathRemainderNegativeDivisor = {
expr = self.math.remainder 54.5 (-20.5); expr = self.math.remainder 54.5 (-20.5);
expected = 13.5; expected = -7;
}; };
testMathRemainderBothNegatives = { testMathRemainderNegativeOperands = {
expr = self.math.remainder (-54.5) (-20.5); expr = self.math.remainder (-54.5) (-20.5);
expected = -13.5; expected = -13.5;
}; };