0
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

Pythonでベクトルの計算を行う方法

Last updated at Posted at 2024-07-02

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次元以上でも同じようにしてなす角を求めることができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0