LoginSignup
7
8

More than 3 years have passed since last update.

numpyを使って2つのベクトルの成す角を求める。

Last updated at Posted at 2019-04-07

2つのベクトルの成す角を求めたい。

ベクトルの内積を学習すると、必ず出てくるのが2つのベクトルの成す角を求める演習問題です。
今回はこの定番の演習問題をPythonを使って解いてみたいと思います。


まず2つのベクトルのインプットできる状態にする。

コード内でベクトルを決めてしまうのではなく、入力待ちの状態にすることにします。

import numpy as np

a = list(map(int, input().split()))
b = list(map(int, input().split()))
A = np.array(a)
B = np.array(b)

内積を計算。

今回はnumpyを使ってしまいましょう。(;^_^A


x = np.inner(A,B)
print(x)

各ベクトルの長さを計算。

これもnumpyを使えばあっという間ですね。

s = np.linalg.norm(A)
t = np.linalg.norm(B)
print(s)
print(t)

2つのベクトルの成す角を求める。

あとは、逆三角関数arccosを使えばおしまい。


theta = np.arccos(x/(s*t))
print(theta)

コサイン類似度

余談ですが、ベクトル間の類似度を求める時には以下のコサイン類似度がよく用いられます。

def similarity(A,B):
    return x/(s*t)
print(similarity(A,B))
7
8
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
7
8