News:

  • October 18, 2026, 03:12:58 PM

Login with username, password and session length

Author Topic: Modulo gives unexpected result  (Read 9144 times)

Controls Guy

  • Internal Dev
  • Hero Member
  • ****
  • Posts: 3628
  • Darth Ladder
Modulo gives unexpected result
« on: April 22, 2021, 05:11:56 PM »
I have

Code: [Select]
MATH V0 "TICKus() % 5"
and I got 65535 and 65532 in V0, which is written nowhere else in logic and there's no HMI.    How can a modulo operation return a value less than zero (if it's actually thinking -1 or -4), or a value greater than the divisor??
I retract my earlier statement that half of all politicians are crooks.  Half of all politicians are NOT crooks.  There.

franji1

  • Bit Weenie
  • Host Moderator
  • Hero Member
  • *****
  • Posts: 3850
    • Host Engineering
Re: Modulo gives unexpected result
« Reply #1 on: April 22, 2021, 05:26:42 PM »
Modulo with negative numbers gives strange results (negative remainder).

Best to convert it to positive, although not sure what happens when it's -2147483648

ABS(TICKus()) % 5

franji1

  • Bit Weenie
  • Host Moderator
  • Hero Member
  • *****
  • Posts: 3850
    • Host Engineering
Re: Modulo gives unexpected result
« Reply #2 on: April 22, 2021, 05:28:46 PM »
However, realize that TICKus() will go from +2147483647 (0x7FFFFFFF) to -2147483648 (0x80000000) in 1 microsecond

Controls Guy

  • Internal Dev
  • Hero Member
  • ****
  • Posts: 3628
  • Darth Ladder
Re: Modulo gives unexpected result
« Reply #3 on: April 22, 2021, 05:32:32 PM »
Ah, even though 32-bit I was assuming unsigned, not sure why.   
I retract my earlier statement that half of all politicians are crooks.  Half of all politicians are NOT crooks.  There.

Controls Guy

  • Internal Dev
  • Hero Member
  • ****
  • Posts: 3628
  • Darth Ladder
Re: Modulo gives unexpected result
« Reply #4 on: April 22, 2021, 05:38:48 PM »
Just generating a random.    ABS() would work or I can just use (TICKus() & 0x8FFF)%5.

Any better thoughts on an RNG?
I retract my earlier statement that half of all politicians are crooks.  Half of all politicians are NOT crooks.  There.

ADC Product Engineer

  • Hero Member
  • *****
  • Posts: 270
Re: Modulo gives unexpected result
« Reply #5 on: April 22, 2021, 09:28:00 PM »
Why not use RANDINT() or RANDREAL()?

Controls Guy

  • Internal Dev
  • Hero Member
  • ****
  • Posts: 3628
  • Darth Ladder
Re: Modulo gives unexpected result
« Reply #6 on: April 22, 2021, 09:42:51 PM »
Cause of not knowing about them?    ;D
I retract my earlier statement that half of all politicians are crooks.  Half of all politicians are NOT crooks.  There.