I have cython code I'm using to speed up a bottleneck in an otherwise pure python calculation. I have a pair of points in a periodic box of length Lbox (1d case is fine for this question). I need to compute the sign of y-x, and I need to flip this sign when the periodic boundary conditions are operative.
In the absence of PBCs, the following question provides the solution: Is there a standard sign function (signum, sgn) in C/C++?. That solution is what I use to compute the sgn function.
def sgn(x, y):
""" If x > y, returns 1.
If x < y, returns -1.
If x == y, returns 0.
"""
return (y < x) - (x < y)
The sgn_pbc function as written below returns the correct result, but is written inefficiently: the control flow within the sgn_pbc is the culprit for slowing down the PBC version. How can I write sgn_pbc in an analogous way to the sgn function, so that I avoid the clumsy control flow?
def sgn_pbc(x, y, Lbox):
d = abs(x-y)
if d <= Lbox/2.:
return sgn(x, y)
else:
return -1*sgn(x, y)