Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

B. Mathematical Formulas > Dot-Products

Dot-Products

The dot-product is a method of multiplying two vectors. If you have two vectors, a = (a1, a2, a3, ...) and b = (b1, b2, b3, ...), then the dot-product is defined as shown in Figure B-10.

Dot-product with components

Figure B-10. Dot-product with components

Dot-product is easily implemented with this function:

def dotproduct(a,b):
  return sum([a[i]*b[i] for i in range(len(a))])

If θ is the angle between the two vectors, then the dot-product can also be defined as shown in Figure B-11.

Dot-product with angle

Figure B-11. Dot-product with angle

This means that you can use the dot-product to calculate the angle between two vectors:

from math import acos

# Calculates the size of a vector
def veclength(a):
  return sum([a[i] for i in range(len(a))])**.5

# Calculates the angle between two vectors
def angle(a,b):
  dp=dotproduct(a,b)
  la=veclength(a)
  lb=veclength(b)
  costheta=dp/(la*lb)
  return acos(costheta)

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint