Skip to content

Instantly share code, notes, and snippets.

@MattWoodhead
Last active June 24, 2017 11:05
Show Gist options
  • Save MattWoodhead/b2fbab30cd8650a4b63c4b6003d057e7 to your computer and use it in GitHub Desktop.
Save MattWoodhead/b2fbab30cd8650a4b63c4b6003d057e7 to your computer and use it in GitHub Desktop.
A comparison of methods for rounding up a dvision to the nearest whole number
"""
A comparison of methods for rounding upwards on dvision operations. Suprisingly, the fastest method was multiplying
the numerator in the division operation by negative one, using floor division, and then multiplying again by
negative one to arrive at the rounded up answer
Further testing is required on larger numbers (and maybe complex numbers?) to see if the results scale well.
"""
import math
import numpy
# Hardware: FX 8350 @ 4.5GHz, 8Gb 2133
def negative_one(N, D): # 855.73 us for ten thousand loops - *fastest*
for i in range(10001):
a = -(-N//D)
return a
def math_ceiling(N, D): # 4.83 ms for ten thousand loops
for i in range(10001):
a = math.ceil(N/D)
return a
def numpy_ceiling(N, D): # 12.11 ms for ten thousand loops
for i in range(10001):
a = numpy.ceil(N/D)
return a
def modulo_if(N, D): # 1.50 ms for ten thousand loops
for i in range(10001):
if N % D == 0:
a = N//D
else:
a = (N//D)+1
return a
# test numbers
numerator = 10
denominator = 3
# round up functions
print(negative_one(numerator, denominator))
print(math_ceiling(numerator, denominator))
print(numpy_ceiling(numerator, denominator))
print(modulo_if(numerator, denominator))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment