Announcement

Collapse
No announcement yet.

Modulo does not handle negatives as expected

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Modulo does not handle negatives as expected

    Hi, I am having trouble getting attention to what I feel is a kind of fundamental problem with blueprint math. Can someone from Epic please comment on this please? https://answers.unrealengine.com/que...negatives.html

    E.g. -1 % 4 does not return 3, it returns -1.

    Can someone explain why this is desired behavior? I want to iterate through an array backwards and wrap the index counter around to the last index of the array using modulo. This is pretty common desired behavior of modulo.
    Thank you

    #2
    Sorry for the 5-year necroposting, but I been googling furiously for half an hour to figure out how Unreal handles negative numbers on modulo. And this thread is the only relevant result.
    The behavior of mod is highly inconsistent over different languages and math libraries.
    And I agree the backwards wrapping variant is the most convenient one.

    Comment


      #3
      Unreal Engine uses the same modulo as in C++, and C++ rounds toward zero. What does that mean?
      Well, the modulo formula is ((a/b) - round(a/b)) * b. When we round in the "normal" modulo, we round towards negative infinity.
      So, this explains why UE4's mod is kinda weird:
      -1%4
      Normal mod: ((-0.25) - (-1)) * 4 = 3.
      C++ mod: ((-0.25) - (0)) * 4 = -1.
      Hope it helped.

      Comment

      Working...
      X