4 ms·
I run into this issue in javascript all the time. I want a number to basically act like pacman leaving the left or right side of a screen. pure sawtooth functio
by ZenPsycho 8y ago
I run into this issue in javascript all the time. I want a number to basically act like pacman leaving the left or right side of a screen. pure sawtooth function. unfortunately js’s % operator mirrors at zero. so i always end up having to search for this:
Number.prototype.mod = function(n) {
return ((this % n) + n) % n;
}
- antidesitter 8y agoAgreed. In my experience, people want to use this modulo operator (e.g. for implementing a ring buffer or wrap-around as you mentioned), but many languages use the other modulo which leads to all sorts of bugs. It doesn’t make sense to me since this modulo is more natural from both a mathematical and an engineering perspective.
- jacobolus 8y agoIt’s because that’s the way CPUs / C do it. Many other language implementors are too lazy to fix it. I have often been thankful that Python does the right thing, and often frustrated that Javascript does not.
- strainer 8y agoFor javascript mod I use these: 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.
- ZenPsycho 8y agoat very large or very small scales, you expect some level of innaccuracy for any IEEE float op. acceptable level of error always depends on what the program is aiming to do I suppose.
- strainer 8y agoRight, I just wondered about getting 0.00000000001 instead of 0 or the like, but that doesn't seem to happen with modest integer inputs.