numpyを用いることにより、ベクトルを求め、なす角や内積を求めることができる。
理論
以下のようなベクトルがあった場合を考える。
\vec{x} =
\begin{pmatrix}
a \\
b \\
\end{pmatrix}
,
\vec{y}=
\begin{pmatrix}
c \\
d \\
\end{pmatrix}
ベクトルのなす角は以下の式で求めることができる
\theta = \arccos \frac{xy}{|x||y|}
ここのxy
は2つのベクトルの内積である。
内積は以下の式で求めることができる。このθがなす角である。
xy = |x||y|\cos \theta = ac + bd
Numpyを使用し、なす角を求める
import numpy as np
def get_angle_vec(vec1:np.ndarray,vec2:np.ndarray):
'''
2つのベクトルからなす角を求めて返す
Arges:
vec1,vec2:ベクトル np.array([1,0])のような形式
'''
#内積を計算
dot = np.inner(vec1,vec2)
#各ベクトルの長さを計算
s = np.linalg.norm(vec1)
t = np.linalg.norm(vec2)
#なす角の計算
theta = np.arccos(dot/(s*t))
return theta
x = np.array([5,0])
y = np.array([0,1])
theta = get_angle_vec(x, y)
print(theta)#出力 1.5707963267948966 ラジアン
出力結果はラジアン(弧度法)になっているため、度数法に変換するには以下のようにする
import numpy as np
+ import math
def get_angle_vec(vec1:np.ndarray,vec2:np.ndarray):
'''
2つのベクトルからなす角を求めて返す
Arges:
vec1,vec2:ベクトル np.array([1,0])のような形式
'''
#内積を計算
dot = np.inner(vec1,vec2)
#各ベクトルの長さを計算
s = np.linalg.norm(vec1)
t = np.linalg.norm(vec2)
#なす角の計算
theta = np.arccos(dot/(s*t))
return theta
x = np.array([5,0])
y = np.array([0,1])
theta_rad = get_angle_vec(x, y)
+ theta_deg = math.degrees(theta_rad)
print(theta)#出力 90.0
今回は2次元ベクトルで考えたが、3次元以上でも同じようにしてなす角を求めることができる。