[Numpy-discussion] still no cross product for new array type

David M. Cooke cookedm at physics.mcmaster.ca
Mon Aug 15 16:39:32 EDT 2005

Greg Ewing <greg.ewing at canterbury.ac.nz> writes:

> Nadav Horesh wrote:
>> Gary Ruben <gruben at bigpond.net.au>:
>> > Just browsing through the new array PEP to see if there's support
>> for > 3-vector operations, such as cross product, norm, length
>> functions.
>> > Sadly I don't see any.
>> Usually this is within the scope of higher level packages such as
>> ScientificPython.
> I'd like to see at least cross product included somewhere,
> since it's difficult to synthesize efficiently from the
> other operations provided.

I agree. I've added a cross_product() funtion to Numeric in CVS. It'll
do the cross product along any axes of the arrays passed, assuming
that they're of dimensions 2 or 3 (a 2d cross-product returns the
z-component of the equivalent 3d one).

The test cases look like this:

        a = Numeric.array([1,2,3])
        b = Numeric.array([4,5,6])
        assert_eq(Numeric.cross_product(a,b), [-3, 6, -3])
        a = Numeric.array([1,2])
        b = Numeric.array([4,5])
        assert_eq(Numeric.cross_product(a,b), -3)
        a = Numeric.array([[1,2,3], [4,5,6]])
        b = Numeric.array([7, 8, 9])
        assert_eq(Numeric.cross_product(a,b), [[-6,12,-6],[-3,6,-3]])
        a = Numeric.array([[1,2,3], [4,5,6]])
        b = Numeric.array([[10,11,12], [7,8,9]])
        assert_eq(Numeric.cross_product(a,b,axis1=0,axis2=0), [-33,-39,-45])
        assert_eq(Numeric.cross_product(a,b), [[-9,18,-9], [-3,6,-3]])

and the calling sequence like this:

def cross_product(a, b, axis1=-1, axis2=-1):
    """Return the cross product of two vectors.

    The cross product is performed over the last axes of a and b by default,
    and can handle axes with dimensions 2 and 3. For a dimension of 2,
    the z-component of the equivalent three-dimensional cross product is

Someone else can make the infix-operator module :-)

|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca

More information about the NumPy-Discussion mailing list