Nice programing

파이썬은 정수를 다음 100으로 반올림합니다.

nicepro 2020. 11. 6. 20:03
반응형

파이썬은 정수를 다음 100으로 반올림합니다.


이미 수백 번 (말장난은 재미 =) 요청을 받았어야했지만 수레를 반올림하는 기능 만 찾을 수 있습니다. 예를 들어, 정수를 어떻게 반올림 130 -> 200합니까?


반올림은 일반적으로 부동 소수점 숫자에서 수행되며 여기에는 round(가장 가까운 정수로 반올림), math.floor(항상 반올림) 및 math.ceil(항상 반올림 )의 세 가지 기본 함수가 있습니다 .

정수에 대해 묻고 수백으로 반올림하지만 math.ceil2 53 보다 작은 숫자만큼 사용할 수 있습니다 . 를 사용하려면 math.ceil먼저 100으로 나누고 반올림 한 다음 나중에 100을 곱합니다.

>>> import math
>>> def roundup(x):
...     return int(math.ceil(x / 100.0)) * 100
... 
>>> roundup(100)
100
>>> roundup(101)
200

먼저 100으로 나누고 나중에 100으로 곱하면 소수점 두 자리를 오른쪽과 왼쪽으로 "이동" math.ceil하여 수백에서 작동합니다. 10**n수십 ( n = 1), 수천 ( n = 3) 등 으로 반올림하려면 100 대신 사용할 수 있습니다 .

이를 수행하는 또 다른 방법은 부동 소수점 수 (정밀도가 제한됨)를 피하고 대신 정수만 사용하는 것입니다. 정수는 Python에서 임의의 정밀도를 갖기 때문에 모든 크기의 숫자를 반올림 할 수 있습니다. 반올림 규칙은 간단합니다. 100으로 나눈 후 나머지를 찾고 0이 아닌 경우 100에서이 나머지를 더합니다.

>>> def roundup(x):
...     return x if x % 100 == 0 else x + 100 - x % 100

이것은 모든 크기의 숫자에 적용됩니다.

>>> roundup(100)
100
>>> roundup(130)
200
>>> roundup(1234567891234567891)
1234567891234567900L

두 가지 솔루션의 미니 벤치 마크를 작성했습니다.

$ python -m timeit -s 'import math' -s 'x = 130' 'int(math.ceil(x/100.0)) * 100'
1000000 loops, best of 3: 0.364 usec per loop
$ python -m timeit -s 'x = 130' 'x if x % 100 == 0 else x + 100 - x % 100'
10000000 loops, best of 3: 0.162 usec per loop

순수한 정수 솔루션은 솔루션에 비해 2 배 더 빠릅니다 math.ceil.

Thomas는 Boolean 값을 곱하여 트릭을 사용한다는 점을 제외하면 위에서 설명한 것과 동일한 정수 기반 솔루션을 제안했습니다. 이런 식으로 코드를 작성할 때 속도상의 이점이 없다는 것은 흥미 롭습니다.

$ python -m timeit -s 'x = 130' 'x + 100*(x%100>0) - x%100'
10000000 loops, best of 3: 0.167 usec per loop

마지막으로, 101–149에서 100으로 반올림하고 150–199에서 200으로 반올림하려는 경우 (예 : 가장 가까운 100으로 반올림) 내장 round함수가이를 수행 할 수 있습니다.

>>> int(round(130, -2))
100
>>> int(round(170, -2))
200

이 시도:

int(round(130 + 49, -2))

이것은 늦은 답변이지만 기존 답변의 가장 좋은 측면을 결합한 간단한 솔루션이 있습니다. 100up from 의 다음 배수는 x입니다 x - x % -100(또는 원하는 경우 x + (-x) % 100).

>>> x = 130
>>> x -= x % -100  # Round x up to next multiple of 100.
>>> x
200

이것은 빠르고 간단하며 x(John Machin의 답변과 같은) 모든 정수에 대해 올바른 결과를 제공하고 x(Martin Geisler의 답변과 같은) float 인 경우 합리적인 결과를 제공합니다 (부동 소수점 표현에 대한 일반적인 경고 모듈로 ).

>>> x = 0.1
>>> x -= x % -100
>>> x
100.0

다음은 양의 정수의 가장 가까운 배수로 반올림하는 일반적인 방법입니다.

def roundUpToMultiple(number, multiple):
    num = number + (multiple - 1)
    return num - (num % multiple)

샘플 사용법 :

>>> roundUpToMultiple (101, 100)
200
>>> roundUpToMultiple (654, ​​321)
963

내용은 a음이 아닌, b양, 양의 정수 :

>>> rup = lambda a, b: (a + b - 1) // b * b
>>> [(x, rup(x, 100)) for x in (199, 200, 201)]
[(199, 200), (200, 200), (201, 300)]

업데이트 현재 받아 들여지는 대답은 float (x) / float (y)를 float. 이 코드를 참조하십시오.

import math

def geisler(x, y): return int(math.ceil(x / float(y))) * y

def orozco(x, y): return x + y * (x % y > 0) - x % y

def machin(x, y): return (x + y - 1) // y * y

for m, n in (
    (123456789123456789, 100),
    (1234567891234567891, 100),
    (12345678912345678912, 100),
    ):
    print; print m, "m"; print n, "n"
    for func in (geissler, orozco, machin):
        print func(m, n), func.__name__

산출:

123456789123456789 m
100 n
123456789123456800 geisler
123456789123456800 orozco
123456789123456800 machin

1234567891234567891 m
100 n
1234567891234568000 geisler <<<=== wrong
1234567891234567900 orozco
1234567891234567900 machin

12345678912345678912 m
100 n
12345678912345680000 geisler <<<=== wrong
12345678912345679000 orozco
12345678912345679000 machin

다음은 몇 가지 타이밍입니다.

>\python27\python -m timeit -s "import math;x =130" "int(math.ceil(x/100.0))*100"
1000000 loops, best of 3: 0.342 usec per loop

>\python27\python -m timeit -s "x = 130" "x + 100 * (x % 100 > 0) - x % 100"
10000000 loops, best of 3: 0.151 usec per loop

>\python27\python -m timeit -s "x = 100" "(x + 99) // 100 * 100"
10000000 loops, best of 3: 0.0903 usec per loop

int가 x 인 경우 : x + 100 - x % 100

However, as pointed in comments, this will return 200 if x==100.

If this is not the expected behavior, you can use x + 100*(x%100>0) - x%100


Warning: Premature optimizations ahead...

Since so many of the answers here do the timing of this I wanted to add another alternative.

Taking @Martin Geisler 's

def roundup(x):
    return x if x % 100 == 0 else x + 100 - x % 100

(which i like best for several reasons)

but factoring out the % action

def roundup2(x):
    x100= x % 100
    return x if x100 == 0 else x + 100 - x100

Yields a ~20% speed improvement over the original

def roundup3(x):
    x100 = x % 100
    return x if not x100 else x + 100 - x100

Is even better and is ~36% faster then the original

finally I was thinking that I could drop the not operator and change the order of the branches hoping that this would also increase speed but was baffled to find out that it is actually slower dropping back to be only 23% faster then the original.

def roundup4(x):
    x100 = x % 100
    return x + 100 - x100  if x100 else x


>python -m timeit -s "x = 130" "x if x % 100 == 0 else x + 100 - x % 100"
1000000 loops, best of 3: 0.359 usec per loop

>python -m timeit -s "x = 130" "x100 = x % 100"  "x if x100 == 0 else x + 100 - x100"
1000000 loops, best of 3: 0.287 usec per loop

>python -m timeit -s "x = 130" "x100 = x % 100"  "x if not x100 else x + 100 - x100"
1000000 loops, best of 3: 0.23 usec per loop

>python -m timeit -s "x = 130" "x100 = x % 100"  "x + 100 - x100 if x100 else x"
1000000 loops, best of 3: 0.277 usec per loop

explanations as to why 3 is faster then 4 would be most welcome.


Try this:

import math
def ceilm(number,multiple):
    '''Returns a float rounded up by a factor of the multiple specified'''
    return math.ceil(float(number)/multiple)*multiple

Sample usage:

>>> ceilm(257,5)
260
>>> ceilm(260,5)
260

참고URL : https://stackoverflow.com/questions/8866046/python-round-up-integer-to-next-hundred

반응형