I need to port quite a few formulas from C to Python and vice versa. What is the best way to make sure that nothing breaks in the process?
I hope my question doesn\'
Some ways to compute integer division with C semantic is as follows:
def div_c0(a, b):
if (a >= 0) != (b >= 0) and a % b:
return a // b + 1
else:
return a // b
def div_c1(a, b):
q, r = a // b, a % b
if (a >= 0) != (b >= 0) and a % b:
return q + 1
else:
return q
def div_c2(a, b):
q, r = divmod(a, b)
if (a >= 0) != (b >= 0) and a % b:
return q + 1
else:
return q
def mod_c(a, b):
return (a % b if b >= 0 else a % -b) if a >= 0 else (-(-a % b) if b >= 0 else a % b)
def div_c3(a, b):
r = mod_c(a, b)
return (a - r) // b
With timings:
n = 100
l = [x for x in range(-n, n + 1)]
ll = [(a, b) for a, b in itertools.product(l, repeat=2) if b]
funcs = div_c0, div_c1, div_c2, div_c3
for func in funcs:
correct = all(func(a, b) == funcs[0](a, b) for a, b in ll)
print(func.__name__, 'correct:', correct)
%timeit [func(a, b) for a, b in ll]
print()
div_c0 correct: True
100 loops, best of 3: 8.42 ms per loop
div_c1 correct: True
100 loops, best of 3: 10 ms per loop
div_c2 correct: True
100 loops, best of 3: 12.3 ms per loop
div_c3 correct: True
100 loops, best of 3: 13.1 ms per loop
Indicating the first approach to be the fastest.
For implementing C's % using Python see here.