Vector products

From Rosetta Code
Revision as of 14:18, 9 April 2011 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Vector products is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Define a vector having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). If you imagine a graph with the x and y axis being at right angles to each other and having a third, z axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.

Given vectors A = (a1, a2, a3); B = (b1, b2, b3); and C = (c1, c2, c3); then the following common vector products are defined:

  • The dot product
A · B = a1b1 + a2b2 + a3b3; a scalar quantity
  • The cross product
A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1); a vector quantity
  • The scaler triple product
A · (B x C); a scalar quantity
  • The vector triple product
A x (B x C); a vector quantity
Task description

Given the three vectors: a = (3, 4, 5); b = (4, 3, 5); c = (-5, -12, -13):

  1. Create a function to compute the dot product of two vectors.
  2. Create a function to compute the cross product of two vectors.
  3. Create a function to compute the scalar triple product of three vectors.
  4. Create a function to compute the vector triple product of three vectors.
  5. Compute and display: a · b
  6. Compute and display: a x b
  7. Compute and display: a · b x c using the scaler triple product function.
  8. Compute and display: a x b x c using the vector triple product function.
References

Python

<lang python>def crossp(a, b):

   Cross product of two 3D vectors
   assert len(a) == len(b) == 3, 'For 3D vectors only'
   a1, a2, a3 = a
   b1, b2, b3 = b
   return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1)

def dotp(a,b):

   Dot product of two eqi-dimensioned vectors
   assert len(a) == len(b), 'Vector sizes must match'
   return sum(aterm * bterm for aterm,bterm in zip(a, b))

def scalartriplep(a, b, c):

   Scalar triple product of three vectors: "a . (b x c)"
   return dotp(a, crossp(b, c))

def vectortriplep(a, b, c):

   Vector triple product of three vectors: "a x (b x c)"
   return crossp(a, crossp(b, c))

if __name__ == '__main__':

   a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13)
   print("a = %r;  b = %r;  c = %r" % (a, b, c))
   print("a . b =", dotp(a,b))
   print("a x b =", crossp(a,b))
   print("a . (b x c) =", scalartriplep(a, b, c))
   print("a x (b x c) =", vectortriplep(a, b, c))</lang>
Sample output
a = (3, 4, 5);  b = (4, 3, 5);  c = (-5, -12, -13)
a . b = 49
a x b = (5, 5, -7)
a . (b x c) = 6
a x (b x c) = (-267, 204, -3)
Note

The popular numpy package has functions for dot and cross products.