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.

2
  • 1
    So Python behaves just like it is described in the documentation? Outrageous. What is your question here? Commented Mar 28, 2018 at 3:21
  • I was wondering how this worked and how to correct the output to give the position as an absolute value along the cycle. Commented Mar 28, 2018 at 19:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Cool. Do you know any other uses for the normal mod output?
The most popular example would be RSA encryption, but for day to day use, sometimes we need to know what the remainder of an integer division would be.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.