我很久没有使用数学了,这应该是一个简单的问题.
I have been not using math for a long time and this should be a simple problem to solve.
假设我有两个点A:(1,0)和B:(1,-1).
Suppose I have two points A: (1, 0) and B: (1, -1).
我想使用一个程序(Python或任何一种编程语言)来计算A,原点(0,0)和B之间的顺时针角度.它将是这样的:
I want to use a program (Python or whatever programming language) to calculate the clockwise angle between A, origin (0, 0) and B. It will be something like this:
angle_clockwise(point1, point2)请注意,参数的顺序很重要.由于角度计算将是顺时针方向:
Note that the order of the parameters matters. Since the angle calculation will be clockwise:
- 如果我调用angle_clockwise(A,B),它将返回45.
- 如果我调用angle_clockwise(B,A),它将返回315.
换句话说,算法是这样的:
In other words, the algorithm is like this:
有什么办法可以编码此问题?
Is there any way to code this problem?
推荐答案使用两个向量的内积和行列式.如果您想了解其工作原理,那么这实际上就是您应该了解的内容.您需要了解/阅读矢量数学才能理解.
Use the inner product and the determinant of the two vectors. This is really what you should understand if you want to understand how this works. You'll need to know/read about vector math to understand.
请参阅: en.wikipedia/wiki/Dot_product 和 en.wikipedia/wiki/Determinant
from math import acos from math import sqrt from math import pi def length(v): return sqrt(v[0]**2+v[1]**2) def dot_product(v,w): return v[0]*w[0]+v[1]*w[1] def determinant(v,w): return v[0]*w[1]-v[1]*w[0] def inner_angle(v,w): cosx=dot_product(v,w)/(length(v)*length(w)) rad=acos(cosx) # in radians return rad*180/pi # returns degrees def angle_clockwise(A, B): inner=inner_angle(A,B) det = determinant(A,B) if det<0: #this is a property of the det. If the det < 0 then B is clockwise of A return inner else: # if the det > 0 then A is immediately clockwise of B return 360-inner在行列式计算中,您将两个向量连接起来以形成2 x 2矩阵,并为此计算行列式.
In the determinant computation, you're concatenating the two vectors to form a 2 x 2 matrix, for which you're computing the determinant.
更多推荐
计算两点之间的角度(顺时针)
发布评论