Language/Python

[Python] 파이썬에서 음수의 "//" 연산(Floor Division) 이 다른 값을 가지는 이유

Deveun 2021. 5. 6. 03:25

파이썬(3.X)에서

/ 나누기 연산은 float 결과값, //나누기 연산은 int 결과값을 가지는 차이가 있다고 생각하고 있었는데

음수에서 해당 연산을 사용했을 때, 다음과 같이 다른 결과가 나오는 것을 발견했다.

print(-1//2)	# >>> -1
print(1//2)		# >>> 0

 

이유를 찾아보니,

"//" 연산은 Floor Division(바닥함수)로 "실수 이하의 최대 정수를 구하는 함수" 로 정의된다.

==> 내림(round down)

즉, -1 < -1/2(=-0.5) < 0 이기 때문에 -0.5보다 작은 최대 정수인 -1 을 결과값으로 가진다.


[참고]stackoverflow.com/questions/37283786/floor-division-with-negative-number

 

Floor division with negative number

The expression 6 // 4 yields 1, where floor division produces the whole number after dividing a number. But with a negative number, why does -6 // 4 return -2?

stackoverflow.com

 

'Language > Python' 카테고리의 다른 글

[Python] collections모듈 Counter 사용하기  (0) 2021.07.04
[Python] 4_클래스  (0) 2021.05.06
[Python] 파이썬에서 제곱 구하기-pow(), math.pow(), ** 의 차이  (0) 2021.05.06
[Python] 3_함수  (0) 2021.05.03
[Python] 2_제어문  (0) 2021.05.02