modulo on negative numbers

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By gdnc

When I do something like (-1) % 20, I expect the result to be 19, but i’m getting -1 instead. Is there another syntax I should be using to get modular arithmetic that restricts the range to positive numbers less than the thing I’m dividing by?

:bust_in_silhouette: Reply From: avencherus

You can do negative mods with fposmod(-1, 20)

And cast it back to integer if you like, since it returns a float.

thanks for the suggestion! i ended up writing my own mod function because i’m not sure i can trust the rounding on floats

gdnc | 2018-09-09 21:12

Way better function for this purpose is posmod.

You know, if a function has f in it, for float, it most likely has an int counterpart.

Soaku | 2020-03-24 16:40