如图所示,我们要计算任意两个向量之间的夹角。
(图中的坐标数字是估计值,随手给定)
python代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import math AB = [ 1 , - 3 , 5 , - 1 ] CD = [ 4 , 1 , 4.5 , 4.5 ] EF = [ 2 , 5 , - 2 , 6 ] PQ = [ - 3 , - 4 , 1 , - 6 ] def angle(v1, v2): dx1 = v1[ 2 ] - v1[ 0 ] dy1 = v1[ 3 ] - v1[ 1 ] dx2 = v2[ 2 ] - v2[ 0 ] dy2 = v2[ 3 ] - v2[ 1 ] angle1 = math.atan2(dy1, dx1) angle1 = int (angle1 * 180 / math.pi) # print(angle1) angle2 = math.atan2(dy2, dx2) angle2 = int (angle2 * 180 / math.pi) # print(angle2) if angle1 * angle2 > = 0 : included_angle = abs (angle1 - angle2) else : included_angle = abs (angle1) + abs (angle2) if included_angle > 180 : included_angle = 360 - included_angle return included_angle ang1 = angle(AB, CD) print ( "AB和CD的夹角" ) print (ang1) ang2 = angle(AB, EF) print ( "AB和EF的夹角" ) print (ang2) ang3 = angle(AB, PQ) print ( "AB和PQ的夹角" ) print (ang3) ang4 = angle(CD, EF) print ( "CD和EF的夹角" ) print (ang4) ang5 = angle(CD, PQ) print ( "CD和PQ的夹角" ) print (ang5) ang6 = angle(EF, PQ) print ( "EF和PQ的夹角" ) print (ang6) |
结果为
1
2
3
4
5
6
7
8
9
10
11
12
|
AB和CD的夹角 55 AB和EF的夹角 139 AB和PQ的夹角 52 CD和EF的夹角 84 CD和PQ的夹角 107 EF和PQ的夹角 169 |
以上这篇Python 计算任意两向量之间的夹角方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/DSTJWJW/article/details/84258760