Jump to content
Sign in to follow this  
jk336699

Syntax Question on Python

Recommended Posts

Just wondering why -9%2 == 1?

in math, the definition of the remainder is something like

-9 = 4*-2 + (-1)

Then, should it the remainder be (-1)?

Thanks in advance=)

Share this post


Link to post
Share on other sites

http://stackoverflow.com/questions/3883004/negative-numbers-in-python

 

Question asked there:

 

I've found some strange behaviour in python regarding negative numbers:

>>> a = -5
>>> a % 4
3

Could anyone explain what's going on?

Answer given there:

Unlike C or C++, Python's modulo operator (%) always return a number having the same sign as the denominator (divisor). Your expression yields 3 because

 

(-5) % 4 = (-2 × 4 + 3) % 4 = 3

 

It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today is Tuesday (day #2), what is the week day N days before? In Python we can compute with

 

return (2 - N) % 7

 

but in C, if N ≥ 3, we get a negative number which is an invalid number, and we need to manually fix it up by adding 7:

 

int result = (2 - N) % 7;
return result < 0 ? result + 7 : result;

 

There's also some more information in the link if you have access to it. Hope that helps out a bit.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...