Host Engineering Forum

General Category => Do-more CPUs and Do-more Designer Software => Topic started by: Controls Guy on April 22, 2021, 05:11:56 PM

Title: Modulo gives unexpected result
Post by: Controls Guy 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??
Title: Re: Modulo gives unexpected result
Post by: franji1 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
Title: Re: Modulo gives unexpected result
Post by: franji1 on April 22, 2021, 05:28:46 PM
However, realize that TICKus() will go from +2147483647 (0x7FFFFFFF) to -2147483648 (0x80000000) in 1 microsecond
Title: Re: Modulo gives unexpected result
Post by: Controls Guy on April 22, 2021, 05:32:32 PM
Ah, even though 32-bit I was assuming unsigned, not sure why.   
Title: Re: Modulo gives unexpected result
Post by: Controls Guy 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?
Title: Re: Modulo gives unexpected result
Post by: ADC Product Engineer on April 22, 2021, 09:28:00 PM
Why not use RANDINT() or RANDREAL()?
Title: Re: Modulo gives unexpected result
Post by: Controls Guy on April 22, 2021, 09:42:51 PM
Cause of not knowing about them?    ;D