Cross product of two vectors in Python

Viewed 96268

How can I calculate the cross product of two vectors without the use of programming libraries?

E.g given vectors a = (1, 2, 3) and b = (4, 5, 6)

6 Answers

are you asking about the formula for the cross product? Or how to do indexing and lists in python?

The basic idea is that you access the elements of a and b as a[0], a[1], a[2], etc. (for x, y, z) and that you create a new list with [element_0, element_1, ...]. We can also wrap it in a function.

On the vector side, the cross product is the antisymmetric product of the elements, which also has a nice geometrical interpretation.

Anyway, it would be better to give you hints and let you figure it out, but that's not really the SO way, so...

def cross(a, b):
    c = [a[1]*b[2] - a[2]*b[1],
         a[2]*b[0] - a[0]*b[2],
         a[0]*b[1] - a[1]*b[0]]

    return c
import numpy as np
a = np.array([1,0,0])  
b = np.array([0,1,0])  
#print the result    
print(np.cross(a,b))

I defined a successror funtion z,This is to help write the formulas of the cross product In a slightly consise way.here is the code

    from numpy import zeros
    def z(a):
      if a == 0 or a == 1:
       return a+1
      elif a == 2:
       return 0
    n = 3
    i = 0
    v = zeros(n, float)
    v1 = zeros(n, float)
    v2 = zeros(n, float)
    v1[0] = float(input("enter x component of v1 "))
    v1[1] = float(input("enter y component of v1 "))
    v1[2] = float(input("enter z component of v1 "))
    v2[0] = float(input("enter x component of v2 "))
    v2[1] = float(input("enter y component of v2 "))
    v2[2] = float(input("enter z component of v2 "))


    def cp(x, y):
     global i
     while i < n:
      v[i] = x[z(i)]*y[z(z(i))]-x[z(z(i))]*y[z(i)]
      i = i + 1
     return v


    ans = cp(v1, v2)
    print(ans)
Related