Python中两个n维向量之间的角度 [英] Angles between two n-dimensional vectors in Python

查看:232
本文介绍了Python中两个n维向量之间的角度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定Python中两个n维向量之间的角度.例如,输入可以是两个列表,如下所示:[1,2,3,4][6,7,8,9].

I 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].

推荐答案

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)))

注意:当向量的方向相同或相反时,此操作将失败.正确的实现在这里: https://stackoverflow.com/a/13849249/71522

Note: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: https://stackoverflow.com/a/13849249/71522

这篇关于Python中两个n维向量之间的角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆