Quantcast
Channel: JavaScript % (modulo) gives a negative result for negative numbers - Stack Overflow
Viewing all articles
Browse latest Browse all 16

Answer by RARE Kpop Manifesto for JavaScript % (modulo) gives a negative result for negative numbers

$
0
0

Assuming the language you're working with uses truncated division algorithm, this function will simultaneously return the modulo values for truncated division, floored division, and also Euclidean division (plus safe handling of division by zero).

The main advantage of this function is that only one single division is performed to obtain all 3 values, thus avoiding the double-work approach suggested by Mozilla MDN :

((n % d) + d) % d

(Arguments are auto integer truncated, so a divisor of -0.31 has same effect as division by zero)

function triple_mod(___, __, _, ____) {    return sprintf("T:%+d_F:%+d_E:%+d", _ = (____ = (__ = int(__)) == (_ = \                   !!__) || __ == -_ || (___ = int(___)) ==  __ || !___ ||                   ! (_ = ___ % __)) ? (__ ? _ < _ : (_ = log(_)) - _) : _,                   ___ = (____ || (!__ < __) - (___ < !__)) ? _ : _ + __,                         (____ ||  !_ < _) ? _ : _ < +___ ? ___ : _ - __)}

+9007199254738183 +61277761 T:+38898571_F:+38898571_E:+38898571+9007199254738183 -61277761 T:+38898571_F:-22379190_E:+38898571-9007199254738183 +61277761 T:-38898571_F:+22379190_E:+22379190-9007199254738183 -61277761 T:-38898571_F:-38898571_E:+22379190

+4688888899996789   +131071 T:+80187_F:+80187_E:+80187+4688888899996789   -131071 T:+80187_F:-50884_E:+80187-4688888899996789   +131071 T:-80187_F:+50884_E:+50884-4688888899996789   -131071 T:-80187_F:-80187_E:+50884

The function has no declared types because it's truly polymorphic -it accepts integers, floats, and even ASCII numeric strings.

The function contains no hardcoded numbers at all since all thenecessary constants and thresholds are derived on the fly. Rapid handling logic exists for matching inputs, zero-dividend, divisor of ±1, and remainder-less exact division.

All calls to abs(), ceil(), or floor() type functions have been eliminated since the emulated value for Euclidean div benefits from floored-div performing most of the heavy lifting on its behalf.

The call to natural log function "(_ = log(_)) - _" is forobtaining a proper IEEE-754 NaN derived from log(0) - log(0) := (-inf) - (-inf)

So while this function isn't exactly Javascriptper se, it's generic enough it should easily be portable to any language.


Viewing all articles
Browse latest Browse all 16

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>