numpy find the vector angle interval [-pi, +pi]

The numpy.arctan2 function can be used to obtain the included angle of the numpy vector;
thus avoiding the angle error caused by the special value;

Examples:

# 初始化向量
a = np.array([-1.0, 1.0])
b = np.array([0.0, 1.0])
# 单位化(可以不用这一步)
a /= norm(a)
b /= norm(b)
# 夹角cos值
cos_ = np.dot(a,b)/(norm(a)*norm(b))
# 夹角sin值
sin_ = np.cross(a,b)/(norm(a)*norm(b))
arctan2_ = np.arctan2(sin_, cos_)
print("向量{}相对于向量{}的夹角是{:.3f},即{:.3f} pi".format(a,b,arctan2_,arctan2_/np.pi))

Example results:

向量[1. 1.]相对于向量[0. 1.]的夹角是0.785,即0.250 pi
向量[1. 0.]相对于向量[0. 1.]的夹角是1.571,即0.500 pi
向量[-1.  1.]相对于向量[0. 1.]的夹角是-0.785,即-0.250 pi

Successfully convert the angle of the vector to the interval [-pi, +pi]

Source code:

a = np.array([-1.0, 1.0])
a /= norm(a)

b = np.array([0.0, 1.0])
b /= norm(b)

cos_ = np.dot(a,b)/(norm(a)*norm(b))
sin_ = np.cross(a,b)/(norm(a)*norm(b))
arctan2_ = np.arctan2(sin_, cos_)
print("向量{}相对于向量{}的夹角是{:.3f},即{:.3f} pi".format(a,b,arctan2_,arctan2_/np.pi))

Guess you like

Origin blog.csdn.net/ao1886/article/details/113530686