파이썬에 // 연산자에 해당하는 상한선이 있습니까?
//
파이썬 3에서 바닥으로 나누는 연산자에 대해 알아 냈습니다 .
대신 ceil로 나누는 연산자가 있습니까? ( /
파이썬 3에서 부동 소수점 나누기를 수행 하는 연산자 에 대해 알고 있습니다.)
ceil로 나누는 연산자가 없습니다. 당신은 필요 import math
하고 사용math.ceil
거꾸로 바닥 분할을 할 수 있습니다.
def ceildiv(a, b):
return -(-a // b)
이것은 파이썬의 나누기 연산자가 바닥 나누기를 수행하기 때문에 작동합니다 (정수 나누기가 분수 부분을 자르는 C와 달리).
이것은 (손실이있는) 부동 소수점 변환이 없기 때문에 Python의 큰 정수에서도 작동합니다.
다음은 데모입니다.
>>> from __future__ import division # a/b is float division
>>> from math import ceil
>>> b = 3
>>> for a in range(-7, 8):
... print(["%d/%d" % (a, b), int(ceil(a / b)), -(-a // b)])
...
['-7/3', -2, -2]
['-6/3', -2, -2]
['-5/3', -1, -1]
['-4/3', -1, -1]
['-3/3', -1, -1]
['-2/3', 0, 0]
['-1/3', 0, 0]
['0/3', 0, 0]
['1/3', 1, 1]
['2/3', 1, 1]
['3/3', 1, 1]
['4/3', 2, 2]
['5/3', 2, 2]
['6/3', 2, 2]
['7/3', 3, 3]
당신이 할 수있는 (x + (d-1)) // d
나눔 경우 x
로 d
예 (x + 4) // 5
.
항상 인라인으로 할 수 있습니다.
((foo - 1) // bar) + 1
python3에서 이것은 속도에 관심이 있다면 float 나누기를 강제하고 ceil ()을 호출하는 것보다 훨씬 빠릅니다. 필요한 사용을 통해 입증되지 않은 경우에는 안됩니다.
>>> timeit.timeit("((5 - 1) // 4) + 1", number = 100000000)
1.7249219375662506
>>> timeit.timeit("ceil(5/4)", setup="from math import ceil", number = 100000000)
12.096064013894647
math.ceil은 53 비트의 정밀도로 제한됩니다. 큰 정수로 작업하는 경우 정확한 결과를 얻지 못할 수 있습니다.
gmpy2의 libary가 제공 c_div
천장 라운딩을 사용 기능.
면책 조항 : gmpy2를 유지합니다.
솔루션 1 : 부정을 사용하여 바닥을 천장으로 변환
def ceiling_division(n, d):
return -(n // -d)
Reminiscent of the Penn & Teller levitation trick, this "turns the world upside down (with negation), uses plain floor division (where the ceiling and floor have been swapped), and then turns the world right-side up (with negation again)"
Solution 2: Let divmod() do the work
def ceiling_division(n, d):
q, r = divmod(n, d)
return q + bool(r)
The divmod() function gives (a // b, a % b)
for integers (this may be less reliable with floats due to round-off error). The step with bool(r)
adds one to the quotient whenever there is a non-zero remainder.
Solution 3: Adjust the numerator before the division
def ceiling_division(n, d):
return (n + d - 1) // d
Translate the numerator upwards so that floor division rounds down to the intended ceiling. Note, this only works for integers.
Solution 4: Convert to floats to use math.ceil()
def ceiling_division(n, d):
return math.ceil(n / d)
The math.ceil() code is easy to understand, but it converts from ints to floats and back. This isn't very fast and it may have rounding issues. Also, it relies on Python 3 semantics where "true division" produces a float and where the ceil() function returns an integer.
I came here because of binary modular groups, and wanting to interact with both the shared middles of a list. For example [1,2,3,4]
has 2
and 3
.
To interact with the middle of the list and use a ceiling operator:
foo = [1,2,3,4]
length = len(foo)
floor = (len(foo)//2)
ceil = floor+1
floor == 2 #True
ceil == 3 #True
참고URL : https://stackoverflow.com/questions/14822184/is-there-a-ceiling-equivalent-of-operator-in-python
'Programing' 카테고리의 다른 글
특정 프로세스가 32 비트인지 64 비트인지 프로그래밍 방식으로 확인하는 방법 (0) | 2020.08.27 |
---|---|
배열에 다른 배열의 모든 배열 값이 포함되어 있는지 PHP 확인 (0) | 2020.08.27 |
TabBar 이미지의 크기는 얼마입니까? (0) | 2020.08.27 |
T-SQL에서 중복 공백을 단일 공백으로 바꾸기 (0) | 2020.08.27 |
문자가 빈 공간과 같은지 확인하는 방법은 무엇입니까? (0) | 2020.08.27 |