1. はじめに
Pythonで数学的な計算を扱う際、三角関数(sin, cos, tan など)は非常に重要です。特に、物理シミュレーション、ゲーム開発、機械学習、グラフ描画などで活用されます。
この記事では、Pythonの math
モジュールに含まれる以下の関数について、具体的な使い方と実行結果を交えて解説します。
math.sin()
:サイン(正弦)math.cos()
:コサイン(余弦)math.tan()
:タンジェント(正接)math.asin()
:逆サイン(アークサイン)math.acos()
:逆コサイン(アークコサイン)math.atan()
:逆タンジェント(アークタンジェント)
三角関数の基礎から、応用的な使い方、注意点まで丁寧に解説していきます。
2. Pythonの三角関数:math.sin(), math.cos(), math.tan()
2-1. mathモジュールとは
Pythonのmath
モジュールには、数学に関する関数が多数用意されています。その中でも、三角関数を使うにはこのモジュールをインポートする必要があります。
2-2. サイン・コサイン・タンジェントを計算する
角度はラジアン(radian)で指定する必要があります。度数法(°)からラジアンに変換するには math.radians()
を使います。
import math
# 30度をラジアンに変換
angle_deg = 30
angle_rad = math.radians(angle_deg)
# 三角関数の計算
sin_val = math.sin(angle_rad)
cos_val = math.cos(angle_rad)
tan_val = math.tan(angle_rad)
print(f"sin(30°) = {sin_val}")
print(f"cos(30°) = {cos_val}")
print(f"tan(30°) = {tan_val}")
実行結果:
sin(30°) = 0.49999999999999994
cos(30°) = 0.8660254037844387
tan(30°) = 0.5773502691896257
3. 逆三角関数:math.asin(), math.acos(), math.atan()
3-1. 逆関数の概要
逆三角関数は、三角関数の値から角度(ラジアン)を求めたいときに使います。
import math
# 値から角度を求める
val = 0.5
# 逆三角関数の計算(戻り値はラジアン)
asin_rad = math.asin(val)
acos_rad = math.acos(val)
atan_rad = math.atan(val)
# ラジアンを度に変換
asin_deg = math.degrees(asin_rad)
acos_deg = math.degrees(acos_rad)
atan_deg = math.degrees(atan_rad)
print(f"asin(0.5) = {asin_deg}°")
print(f"acos(0.5) = {acos_deg}°")
print(f"atan(0.5) = {atan_deg}°")
実行結果:
asin(0.5) = 30.000000000000004°
acos(0.5) = 60.00000000000001°
atan(0.5) = 26.56505117707799°
4. よくある使い方・応用例
4-1. 三角形の高さを計算する
角度と斜辺の長さから三角形の高さを求める例です。
図形の描画や物理演算でよく使われます。
import math
# 角度(度)と斜辺の長さ
angle_deg = 45
hypotenuse = 10
# ラジアンに変換
angle_rad = math.radians(angle_deg)
# 高さ = 斜辺 × sin(角度)
height = hypotenuse * math.sin(angle_rad)
print(f"高さは {height:.2f}")
実行結果:
高さは 7.07
4-2. atan2で2点間の角度を求める
math.atan2(y, x)
を使うと、2次元平面上の点から角度を計算できます。ゲームやロボットの制御でよく使われます。
import math
# 2点間の差分
dx = 3
dy = 4
# 傾きの角度を計算(ラジアン → 度)
angle_rad = math.atan2(dy, dx)
angle_deg = math.degrees(angle_rad)
print(f"角度は {angle_deg:.2f}°")
実行結果:
角度は 53.13°
5. 注意点・エラー対策
5-1. 度とラジアンの変換ミス
三角関数はラジアン単位で入力する必要があります。
math.radians()
や math.degrees()
を忘れると、思った結果が得られません。
5-2. asin, acosの入力範囲
math.asin()
と math.acos()
に渡す値は -1.0
〜 1.0
に限られます。範囲外の値を渡すと ValueError
が発生します。
import math
# 範囲外の値を渡すとエラー
try:
result = math.asin(1.5)
except ValueError as e:
print(f"エラー: {e}")
実行結果:
エラー: math domain error
6. まとめ
math.sin()
,math.cos()
,math.tan()
で三角関数の値を取得math.asin()
,math.acos()
,math.atan()
で角度を取得- 入力値の単位(ラジアンと度)に注意
Pythonの三角関数は、図形描画・物理シミュレーション・AI制御など多くの場面で活躍します。
計算精度も高く、応用力を高めるにはとても良いテーマです。Python学習の中でも、ぜひマスターしておきたい分野です。