Mod Function and Negative Numbers (2000)
mathforum.org
mathforum.org
div(x,y) # truncated division; quotient rounded towards zero
fld(x,y) # floored division; quotient rounded towards -Inf
and correspondingly rem(x,y) # remainder; satisfies x == div(x,y)*y + rem(x,y); sign matches x
mod(x,y) # modulus; satisfies x == fld(x,y)*y + mod(x,y); sign matches y
and the convenience functions divrem(x,y) # returns (div(x,y),rem(x,y)) ## Lotus 123 convention
fldmod(x,y) # returns (fld(x,y),mod(x,y)) ## Excel convention
(There's also mod1 and fld1, and there's mod2pi(x) which is more precise than mod(x, 2pi).) Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}I have often been thankful that Python does the right thing, and often frustrated that Javascript does not.
function modn(a,b){ return a-Math.round(a/b)*b }
// this returns in the cycle -0.5 to 0.5
function modp(a,b){ return a-Math.floor(a/b)*b }
// this returns 0 to 1 (times the cycle `b`)
They can actually run faster than the % operator for some reason, although not if put on Numbers prototype which is still quite slow on latest engines.I ran a quick check on possible rounding differences with % - compared results of a few million very large random number inputs:
For positive Integers modp(a,b) returns identically to a%b
For positive reals 8% of returns differ by about 1 ulp.
quot :: a -> a -> a
integer division truncated toward zero
rem :: a -> a -> a
integer remainder, satisfying
(x `quot` y)*y + (x `rem` y) == x
div :: a -> a -> a
integer division truncated toward negative infinity
mod :: a -> a -> a
integer modulus, satisfying
(x `div` y)*y + (x `mod` y) == x
Here's an example ghci> (-340) `divMod` 60
(-6,20)
ghci> (-340) `quotRem` 60
(-5,-40)Truncated?
>>> a = [1, 2, 3]
>>> a[-1]
3
>>> a[-2]
2
>>> a[-3]
1
>>> a[-4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range