What is fposmod()

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By avencherus
:warning: Old Version Published before Godot 3 was released.

Was curious about this function, and why it’s different than fmod(). It says something vague about wrapping equally in negative and positive.

Can anyone share what it’s about?

Thanks.

:bust_in_silhouette: Reply From: ingo_nikot
print(fmod(-7,10)) # -7
print(fposmod(-7,10)) #3

they behave diffrent when it comes to negative values. Afaik the first one is the one for euclidean divison.

Yeah the implementation is:

return (p_x>=0) ? Math::fmod(p_x,p_y) : p_y-Math::fmod(-p_x,p_y);

I’m wondering about it’s application though. Does it go by another name?

avencherus | 2017-01-25 08:52

Mathematically, the function that returns -7 is called the Remainder function (Rem) and the function that returns 3 is called the Modulus function (Mod). It’s more common to implement the Remainer instead of the Modulus as it is easier to write and works fast for positive values.

anonymous | 2018-03-21 02:37

:bust_in_silhouette: Reply From: avencherus

To answer this old post, it is useful for wrapping numbers in a positive or negative direction. Modulus wraps in the positive direction only.

I had an issue understanding it, because the old implementation was wrong. It has since been fixed.

As an example, looping backwards through an array, but wanting to wrap back to the end.

[0, 1, 2, 3, 4]

If at index 0, and subtracting 1, it would go to index -1. With that index and the array size of 5, fposmod(-1, 5) would return 4, wrapping back to the end of that array while travelling in the negative direction.