Cross product of two vectors in Python

后端 未结 5 754
盖世英雄少女心
盖世英雄少女心 2021-02-18 13:25

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)

相关标签:
5条回答
  • 2021-02-18 13:49

    If you want to implement the cross product yourself you may see http://en.wikipedia.org/wiki/Vector_cross_product or a math/physics book. Shortly (a1, a2, a3) X (b1, b2, b3) = (a2*b3-a3*b2, a3*b1-a1*b3, a1*b2-a2*b1)

    0 讨论(0)
  • 2021-02-18 14:01

    for multiple dimensions, this might work;

        def crossProd(a,b):
          dimension = len(a)
          c = []
          for i in range(dimension):
            c.append(0)
            for j in range(dimension):
              if j <> i:
                for k in range(dimension):
                  if k <> i:
                    if k > j:
                      c[i] += a[j]*b[k]
                    elif k < j:
                      c[i] -= a[j]*b[k]
          return c
    
    0 讨论(0)
  • 2021-02-18 14:04
    import numpy as np
    a = np.array([1,0,0])  
    b = np.array([0,1,0])  
    #print the result    
    print(np.cross(a,b))
    
    0 讨论(0)
  • 2021-02-18 14:08

    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
    
    0 讨论(0)
  • 2021-02-18 14:09

    I did it like this:

    def cross_product(u,v):  
        dim = len(u)
        s = []
        for i in range(dim):
            if i == 0:
                j,k = 1,2
                s.append(u[j]*v[k] - u[k]*v[j])
            elif i == 1:
                j,k = 2,0
                s.append(u[j]*v[k] - u[k]*v[j])
            else:
                j,k = 0,1
                s.append(u[j]*v[k] - u[k]*v[j])
        return s
    
    0 讨论(0)
提交回复
热议问题