4 ms·
For 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-M
by strainer 8y ago
For 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.