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;
/* Similar to the nixpkgs' `trivial.mod` but retain the decimal values. This
is just an approximation from ECMAScript's implementation of the modulo
operator (%) which is more like a remainder operator.
is just an approximation from ECMAScript's implementation of the remainder
operator.
Type: remainder :: Number -> Number -> Number
@ -274,20 +274,11 @@ rec {
remainder (-54) (-4)
=> -2
*/
remainder = base: number:
remainder = dividend: divisor:
let
base' = abs base;
number' = abs number;
difference = number' * ((floor (base' / number')) + 1);
result = abs (number' - (difference - base'));
quotient = dividend / divisor;
in
if number' > base'
then base
else
if base < 0
then -(result)
else result;
dividend - ((floor quotient) * divisor);
/* 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;
};
testMathRemainderBothPositive = {
testMathRemainderPositiveOperands = {
expr = self.math.remainder 54.5 20.5;
expected = 13.5;
};
testMathRemainderNegativeBase = {
testMathRemainderNegativeDividend = {
expr = self.math.remainder (-54.5) 20.5;
expected = -13.5;
expected = 7;
};
testMathRemainderNegativeNumber = {
testMathRemainderNegativeDivisor = {
expr = self.math.remainder 54.5 (-20.5);
expected = 13.5;
expected = -7;
};
testMathRemainderBothNegatives = {
testMathRemainderNegativeOperands = {
expr = self.math.remainder (-54.5) (-20.5);
expected = -13.5;
};