views:

285

answers:

3

In need to determine the angle(s) between two n-dimensional vectors in Python. For example, the input can be two lists like the following: [1,2,3,4] and [6,7,8,9].

Can anybody help me? Thanks in advance!

A: 

You'll be wanting this formula.

Ignacio Vazquez-Abrams
+2  A: 

Using numpy (highly recommended), you would do:

u = array([1.,2,3,4])
v = ...
c = dot(u,v)/norm(u)/norm(v) # -> cosine of the angle
angle = arccos(c) # if you really want the angle
Olivier
+8  A: 
import math

def dotproduct(v1, v2):
  return sum((a*b) for a, b in zip(v1, v2))

def length(v):
  return math.sqrt(dotproduct(v, v))

def angle(v1, v2):
  return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))
Alex Martelli
Also, if you only need cos, sin, tan of angle, and not the angle itself, then you can skip the math.acos to get cosine, and use cross product to get sine.
mbeckish
This is exactly what i was looking for, thank you!
Peter
Given that `math.sqrt(x)` is equivalent to `x**0.5` and `math.pow(x,y)` is equivalent to `x**y`, I'm surprised these survived the redundancy axe wielded during the Python 2.x->3.0 transition. In practice, I'm usually doing these kinds of numeric things as part of a larger compute-intensive process, and the interpreter's support for '**' going directly to the bytecode BINARY_POWER, vs. the lookup of 'math', the access to its attribute 'sqrt', and then the painfully slow bytecode CALL_FUNCTION, can make a measurable improvement in speed at no coding or readability cost.
Paul McGuire