programing

파이썬에서 음수에 대한 모듈로 연산

nasanasas 2020. 12. 7. 08:12
반응형

파이썬에서 음수에 대한 모듈로 연산


음수와 관련하여 Python에서 이상한 동작을 발견했습니다.

>>> -5 % 4
3

아무도 무슨 일이 일어나고 있는지 설명 할 수 있습니까?


C 또는 C ++와 달리 Python의 모듈로 연산자 ( %)는 항상 분모 (제수)와 동일한 부호를 갖는 숫자를 반환합니다. 당신의 표현은 3을 산출합니다.

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

음이 아닌 결과가 종종 더 유용하기 때문에 C 동작보다 선택됩니다. 예를 들어 요일을 계산하는 것입니다. 오늘이 화요일 (2 일) 인 경우 N 일 전의 요일은 무엇 입니까? 파이썬에서는 다음과 같이 계산할 수 있습니다.

return (2 - N) % 7

그러나 C에서 N ≥ 3이면 잘못된 숫자 인 음수를 얻고 7을 더하여 수동으로 수정해야합니다.

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

( 다른 언어에 대해 결과 기호가 결정되는 방법 http://en.wikipedia.org/wiki/Modulo_operator참조하십시오 .)


Guido van Rossum의 설명은 다음과 같습니다.

http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html

본질적으로 a / b = q와 나머지 r은 b * q + r = a 및 0 <= r <b의 관계를 유지합니다.


음수로 정수 나누기와 모드를 처리하는 가장 좋은 방법은 없습니다. a/b같은 크기이고 반대 부호 이면 좋을 것 입니다 (-a)/b. a % b실제로 모듈로 b 라면 좋을 것 입니다. 우리가 정말로 원하기 때문에 a == (a/b)*b + a%b처음 두 개는 호환되지 않습니다.

어느 쪽을 지킬 것인가는 어려운 질문이며 양측 모두에 대한 논쟁이 있습니다. C와 C ++는 정수 나눗셈을 0 (so a/b == -((-a)/b)) 으로 반올림 하며 Python은 그렇지 않습니다.


지적했듯이 Python 모듈로는 다른 언어의 규칙에 대한 합당한 예외를 만듭니다 .

이는 특히 모듈로가 자주 사용되는 //것처럼 정수 나누기 연산자 와 함께 사용할 때 음수에 원활한 동작을 제공합니다 %(math. divmod 에서와 같이 ).

for n in range(-8,8):
    print n, n//4, n%4

생성 :

 -8 -2 0
 -7 -2 1
 -6 -2 2
 -5 -2 3

 -4 -1 0
 -3 -1 1
 -2 -1 2
 -1 -1 3

  0  0 0
  1  0 1
  2  0 2
  3  0 3

  4  1 0
  5  1 1
  6  1 2
  7  1 3
  • 파이썬 %은 제수가 양수일 때 항상 0 또는 양수를 출력합니다.
  • 파이썬은 //항상 음의 무한대로 반올림합니다.

4에 대한 모듈로 등가 클래스 :

  • 0 : 0, 4, 8, 12 ... 및 -4, -8, -12 ...
  • 1 : 1, 5, 9, 13 ... 및 -3, -7, -11 ...
  • 2 : 2, 6, 10 ... 및 -2, -6, -10 ...
  • 3: 3, 7, 11... and -1, -5, -9...

Here's a link to modulo's behavior with negative numbers. (Yes, I googled it)


I also thought it was a strange behavior of Python. It turns out that I was not solving the division well (on paper); I was giving a value of 0 to the quotient and a value of -5 to the remainder. Terrible... I forgot the geometric representation of integers numbers. By recalling the geometry of integers given by the number line, one can get the correct values for the quotient and the remainder, and check that Python's behavior is fine. (Although I assume that you have already resolved your concern a long time ago).


It's also worth to mention that also the division in python is different from C: Consider

>>> x = -10
>>> y = 37

in C you expect the result

0

what is x/y in python?

>>> print x/y
-1

and % is modulo - not the remainder! While x%y in C yields

-10

python yields.

>>> print x%y
27

You can get both as in C

The division:

>>> from math import trunc
>>> d = trunc(float(x)/y)
>>> print d
0

And the remainder (using the division from above):

>>> r = x - d*y
>>> print r
-10

This calculation is maybe not the fastest but it's working for any sign combinations of x and y to achieve the same results as in C plus it avoids conditional statements.

참고URL : https://stackoverflow.com/questions/3883004/the-modulo-operation-on-negative-numbers-in-python

반응형