![]() |
Forum Index : Microcontroller and PC projects : MOD (modulo) operator strangeness
Author | Message | ||||
daveculp Newbie ![]() Joined: 02/07/2020 Location: United StatesPosts: 22 |
Im writing a game of life and I wanted the board to wrap around. Normally I do this with the modulo operator. Example: The left most column (0) should wrap around to the right most column (49). So, if I want to get the state of that cell I could do something like this (in Python) num_neighbors += board[row] [ (col-1) % NUM_C] If col = 0 and NUM_C represents the max number of columns (50),this would result in -1%50 Which would be 49 and therefore wraps around to the last (50th) column (starting from 0). I tried this on the CMM2 and it claims the statement -1 MOD 50 is -1. That doesn't seem right. |
||||
daveculp Newbie ![]() Joined: 02/07/2020 Location: United StatesPosts: 22 |
I can write my own modulus function doing something like this: PRINT modulus(-1,50) FUNCTION modulus (numerator, denominator) AS INTEGER modulus=numerator-INT(numerator/denominator)*denominator END FUNCTION This properly returns 49 Edited 2020-07-06 11:08 by daveculp |
||||
daveculp Newbie ![]() Joined: 02/07/2020 Location: United StatesPosts: 22 |
Well, I just learned that using negative numbers with modulo is "undefined" and different in different languages. https://en.wikipedia.org/wiki/Modulo_operation "When either a or n is negative, the naive definition breaks down, and programming languages differ in how these values are defined." I will just use my function above. |
||||
KeepIS![]() Guru ![]() Joined: 13/10/2014 Location: AustraliaPosts: 1872 |
Thanks for following this one through, another thing to put in the notes. Mike. NANO Inverter: Full download - Only Hex Ver 8.1Ks |
||||
TassyJim![]() Guru ![]() Joined: 07/08/2011 Location: AustraliaPosts: 6269 |
My way of catching small negative numbers is to add the divisor to the dividend first. a = -1 b = 50 print a mod b print (a+b) mod b If you are likely to have big excursions, make it a multiple of the divisor. Jim VK7JH MMedit |
||||
![]() |
![]() |
The Back Shed's forum code is written, and hosted, in Australia. | © JAQ Software 2025 |