Skip to content

Instantly share code, notes, and snippets.

@mikaem
Last active January 22, 2016 10:16
Show Gist options
  • Save mikaem/46d7fdbab7ab6fe276ee to your computer and use it in GitHub Desktop.
Save mikaem/46d7fdbab7ab6fe276ee to your computer and use it in GitHub Desktop.
Test of various cross products with NumPy
from numpy import *
N = 10
a = zeros((3, N, N, N))+1
b = zeros((3, N, N, N))+2
c = zeros((3, N, N, N))
a1 = zeros((N, N, N, 3))+1
b1 = zeros((N, N, N, 3))+2
c1 = zeros((N, N, N, 3))
def cross1(c, a, b):
c[0] = a[1]*b[2] - a[2]*b[1]
c[1] = a[2]*b[0] - a[0]*b[2]
c[2] = a[0]*b[1] - a[1]*b[0]
return c
def cross2(c, a, b):
c[:] = cross(a, b, axisa=0, axisb=0, axisc=0)
return c
def cross3(c, a, b):
c[..., 0] = a[..., 1]*b[..., 2] - a[..., 2]*b[..., 1]
c[..., 1] = a[..., 2]*b[..., 0] - a[..., 0]*b[..., 2]
c[..., 2] = a[..., 0]*b[..., 1] - a[..., 1]*b[..., 0]
return c
def cross4(c, a, b):
c[:] = cross(a, b, axisa=3, axisb=3, axisc=3)
return c
if __name__ == "__main__":
import timeit
print timeit.timeit("c = cross1(c, a, b)", setup="from __main__ import cross1, c, a, b", number=100)
print timeit.timeit("c = cross2(c, a, b)", setup="from __main__ import cross2, c, a, b", number=100)
print timeit.timeit("c1 = cross3(c1, a1, b1)", setup="from __main__ import cross3, c1, a1, b1", number=100)
print timeit.timeit("c1 = cross4(c1, a1, b1)", setup="from __main__ import cross4, c1, a1, b1", number=100)
@mikaem
Copy link
Author

mikaem commented Jan 22, 2016

Running it on my computer shows that first option is fastest
In [1]: run test_cross
0.00189399719238
0.0251979827881
0.00320816040039
0.0264158248901

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment