4 ms·
The other point is that remainder makes much more sense for floating point numbers, as it's exact. mod on the other hand is not, and is fiendishly difficult to
by simonbyrne 8y ago
The other point is that remainder makes much more sense for floating point numbers, as it's exact. mod on the other hand is not, and is fiendishly difficult to get "right" (if that is even possible).
- jacobolus 8y agoIn what context do you use it? I use a “mod” operator all the time for floating point calculations, and have never come across a need for the other one. As one simple example, it is frequently useful to map floats into the range [0, 2π), but I have never once wanted to map positive floats into the range [0, 2π) while negative floats get mapped into (–2π, 0] by the same code.
- simonbyrne 8y agoWell, I have indeed spent more time thinking about this than is probably healthy, but here are some nice edge cases to think about: - https://github.com/JuliaLang/julia/issues/14826 https://github.com/JuliaLang/julia/issues/14826 mod(-eps(), 4.0) - https://github.com/JuliaLang/julia/issues/17415 https://github.com/JuliaLang/julia/issues/17415 fld(1.0,0.2) - https://github.com/JuliaLang/julia/issues/3127 https://github.com/JuliaLang/julia/issues/3127 mod(1.0,0.1) - https://github.com/JuliaLang/julia/issues/3104 https://github.com/JuliaLang/julia/issues/3104 mod(0.95,0.01) I'm pretty sure there are more issues. re: mod 2pi, typically it is most accurate to reduce to (-pi,pi) (i.e. division rounding to nearest). Also to get it accurate you need fancy range reduction algorithms, hence julia has rem2pi https://docs.julialang.org/en/stable/base/math/#Base.Math.rem2pi https://docs.julialang.org/en/stable/base/math/#Base.Math.re...
- jacobolus 8y agoWithout knowing the intended use case of the code, the edge case behavior in some of these cases is pretty meaningless. Different behavior might make sense in different applications, and in many applications the choice is largely irrelevant. Whichever one you choose someone who wants the other version will have to work around it. These examples don’t really have much bearing on the general usefulness of “remainder” vs. “modulo” though.