0

I'm working on a modular sorter in python3 and have noticed weird behavior to do with the signs of input variables when taking the mod. I intend for it to sort a value by the remainder after dividing by the cycle length.

I.e., c = 4 / 14 = 0 r **4**", "c = 18 / 14 = 1 r **4**", and "c = 32 / 14 = 2 r **4**

All of these are 4th position values because they leave 4. However, if any of the input variables are negative, the result is not what I intend. Any ideas as to how this works (I might use this weird functionality in later coding)?

a = 4     #the value for sorting
b = 14    #the length of the cycle before it reaches the 0 position

def modS(val, cyc):
    c = val % cyc
    print(c)

modS(a, b)

E.g.,

a = 4
b = 14

prints 4

a = -4
b = 14

prints 10

a = 4
b = -14

prints -10

a = -4
b = -14

prints -4

These printed values might be useful for stuff like pH calculations, but not for my purposes.

Balwinder Singh
  • 2,272
  • 5
  • 23
  • 34
Mr. Sir
  • 17
  • 2
  • 1
    So Python behaves just like it is described in the documentation? Outrageous. What is your question here? – Mr. T Mar 28 '18 at 03:21
  • I was wondering how this worked and how to correct the output to give the position as an absolute value along the cycle. – Mr. Sir Mar 28 '18 at 19:00

1 Answers1

0

I can't comment yet to specify, so I'll try to answer what I think you're trying to ask

Trying to get the answer you want even when it's negative

I'd recommend using the abs() method to treat all the numbers as positive, e.g.,

def modS(val, cyc):
    c = abs(val) % abs(cyc)
    print(c)

which gives 4 for your data set.

Otherwise, if you're just interested to know why it happens, I recommend reading this other question about the same thing.

Community
  • 1
  • 1
  • 1
    Cool. Do you know any other uses for the normal mod output? – Mr. Sir Mar 28 '18 at 19:02
  • The most popular example would be [RSA encryption](https://simple.wikipedia.org/wiki/RSA_algorithm), but for day to day use, sometimes we need to know what the remainder of an integer division would be. – William Torkington Apr 11 '19 at 02:26