Python math.cos()とは?コサイン(余弦)の使い方を解説
Pythonのmath.cos()は、コサイン(余弦)を計算する関数です。
三角関数のひとつで、角度から比率を求めます。図形の座標計算のほか、機械学習のコサイン類似度でも中心的な役割を果たします。
この記事では、math.cos()の使い方を実践例つきで解説します。
math.cos()の基本的な使い方
import math
print(math.cos(0))
print(math.cos(math.pi / 2))
print(math.cos(math.pi))
実行結果:
1.0
6.123233995736766e-17
-1.0
戻り値は-1.0から1.0の範囲のfloatです。
cos(0)が1.0である点が、sin(0)が0.0であるのと対照的です。
引数はラジアン
math.cos()も、引数はラジアンです。度数をそのまま渡すと違う値になります。
import math
print(math.cos(60))
print(math.cos(math.radians(60)))
実行結果:
-0.9524129804151563
0.5000000000000001
60度のコサインは0.5です。math.radians()を通すのを忘れないでください。
import math
def cos_deg(deg):
return math.cos(math.radians(deg))
for d in [0, 30, 45, 60, 90, 180]:
print(f"{d:>3}度 → {cos_deg(d):>7.4f}")
実行結果:
0度 → 1.0000
30度 → 0.8660
45度 → 0.7071
60度 → 0.5000
90度 → 0.0000
180度 → -1.0000
sinとcosの関係
2つの関数は、90度ずれた同じ波です。
import math
for d in [0, 90, 180, 270]:
r = math.radians(d)
print(f"{d:>3}度 sin={math.sin(r):>6.2f} cos={math.cos(r):>6.2f}")
実行結果:
0度 sin= 0.00 cos= 1.00
90度 sin= 1.00 cos= 0.00
180度 sin= 0.00 cos= -1.00
270度 sin= -1.00 cos= -0.00
有名な公式も確認できます。
import math
r = math.radians(37)
print(math.sin(r) ** 2 + math.cos(r) ** 2)
実行結果:
1.0
sin²θ + cos²θ = 1という関係です。どんな角度でも成り立ちます。
実践例|円周上に点を配置する
import math
def circle_points(n, radius=100):
points = []
for i in range(n):
rad = math.radians(360 / n * i)
points.append((radius * math.cos(rad), radius * math.sin(rad)))
return points
for x, y in circle_points(6):
print(f"x={x:>8.2f}, y={y:>8.2f}")
実行結果:
x= 100.00, y= 0.00
x= 50.00, y= 86.60
x= -50.00, y= 86.60
x= -100.00, y= 0.00
x= -50.00, y= -86.60
x= 50.00, y= -86.60
正六角形の頂点座標が求まりました。x座標がcos、y座標がsinです。
円グラフの描画やアイコンの円形配置に応用できます。
実践例|コサイン類似度
機械学習や検索で使われる、2つのベクトルの「向きの近さ」を測る指標です。
import math
def cosine_similarity(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
v1 = [1, 2, 3]
v2 = [2, 4, 6]
v3 = [-1, -2, -3]
print(cosine_similarity(v1, v2))
print(cosine_similarity(v1, v3))
実行結果:
1.0
-1.0
| 値 | 意味 |
|---|---|
| 1に近い | 向きがほぼ同じ(似ている) |
| 0に近い | 無関係 |
| -1に近い | 正反対 |
文書を単語の出現回数のベクトルにすれば、文書同士の類似度が測れます。
import math
from collections import Counter
def to_vector(text, vocab):
c = Counter(text.split())
return for w in vocab]
docs = ["python java python", "python python php"]
vocab = sorted({w for d in docs for w in d.split()})
v1 = to_vector(docs[0], vocab)
v2 = to_vector(docs[1], vocab)
print(vocab)
print(v1, v2)
print(f"類似度: {cosine_similarity(v1, v2):.3f}")
実行結果:
['java', 'php', 'python']
[1, 0, 2] [0, 1, 2]
類似度: 0.800
「コサイン」類似度という名前は、この値が2つのベクトルがなす角のコサインに等しいことに由来します。角度に戻すこともできます。
import math
sim = 0.8
print(f"なす角: {math.degrees(math.acos(sim)):.1f}度")
実行結果:
なす角: 36.9度
実践例|2点間の距離(余弦定理)
import math
def third_side(a, b, angle_deg):
rad = math.radians(angle_deg)
return math.sqrt(a ** 2 + b ** 2 - 2 * a * b * math.cos(rad))
print(third_side(3, 4, 90))
print(third_side(5, 5, 60))
実行結果:
5.0
5.0
90度のときは三平方の定理(3:4:5)と一致します。cos(90°) = 0なので、最後の項が消えるためです。
逆関数のacos()
import math
print(math.degrees(math.acos(0.5)))
print(math.degrees(math.acos(1.0)))
print(math.degrees(math.acos(-1.0)))
実行結果:
60.00000000000001
0.0
180.0
値から角度を求める関数です。引数は-1〜1の範囲でなければエラーになります。
import math
math.acos(1.0000001)
実行結果:
ValueError: math domain error
計算誤差でわずかに1を超えることがあるため、実務では範囲を制限しておくと安全です。
import math
def safe_acos(x):
return math.acos(max(-1.0, min(1.0, x)))
print(math.degrees(safe_acos(1.0000001)))
math.cos()まとめ
| ポイント | 内容 |
|---|---|
| 構文 | math.cos(x) |
| 引数 | ラジアン |
| 戻り値 | -1.0〜1.0のfloat |
cos(0) |
1.0 |
| 度数を使うとき | math.radians()で変換 |
| x座標 | 半径 × cos(角度) |
| 角度を求める | math.acos()(誤差対策が必要) |
図形の座標計算とコサイン類似度——この2つが、実務でmath.cos()に出会う主な場面です。






