PYTHON MEBY

Pythonで三角関数を計算(math.sin, math.cos, math.tan, etc.)

この記事では、Pythonのmathモジュールを使用して三角関数(sin, cos, tan, asin, acos, atan, etc.)を計算する方法を説明します。サンプルコード付きで解説します。

目次

math.sin(): 正弦(サイン)

math.sin()は、与えられた角度の正弦(サイン)を返します。角度はラジアンで指定する必要があります。

import math
angle_rad = math.pi / 2  # 90度
sin_value = math.sin(angle_rad)
print(f"sin({angle_rad} rad) = {sin_value}")

出力:sin(1.5707963267948966 rad) = 1.0

math.cos(): 余弦(コサイン)

math.cos()は、与えられた角度の余弦(コサイン)を返します。角度はラジアンで指定する必要があります。

import math
angle_rad = 0  # 0度
cos_value = math.cos(angle_rad)
print(f"cos({angle_rad} rad) = {cos_value}")

出力:cos(0 rad) = 1.0

math.tan(): 正接(タンジェント)

math.tan()は、与えられた角度の正接(タンジェント)を返します。角度はラジアンで指定する必要があります。

import math
angle_rad = math.pi / 4  # 45度
tan_value = math.tan(angle_rad)
print(f"tan({angle_rad} rad) = {tan_value}")

出力:tan(0.7853981633974483 rad) = 0.9999999999999999

math.asin(): 逆正弦(アークサイン)

math.asin()は、与えられた正弦値に対応する角度(ラジアン)を返します。返される角度の範囲は[-π/2, π/2]です。

import math
sin_value = 1.0
angle_rad = math.asin(sin_value)
print(f"asin({sin_value}) = {angle_rad} rad")

出力:asin(1.0) = 1.5707963267948966 rad

math.acos(): 逆余弦(アークコサイン)

math.acos()は、与えられた余弦値に対応する角度(ラジアン)を返します。返される角度の範囲は[0, π]です。

import math
cos_value = 0.0
angle_rad = math.acos(cos_value)
print(f"acos({cos_value}) = {angle_rad} rad")

出力:acos(0.0) = 1.5707963267948966 rad

math.atan(): 逆正接(アークタンジェント)

math.atan()は、与えられた正接値に対応する角度(ラジアン)を返します。返される角度の範囲は[-π/2, π/2]です。

import math
tan_value = 1.0
angle_rad = math.atan(tan_value)
print(f"atan({tan_value}) = {angle_rad} rad")

出力:atan(1.0) = 0.7853981633974483 rad

math.atan2(): 2引数の逆正接

math.atan2(y, x)は、点(x, y)の偏角(角度)をラジアンで返します。返される角度の範囲は[-π, π]です。

import math
y = 1.0
x = 1.0
angle_rad = math.atan2(y, x)
print(f"atan2({y}, {x}) = {angle_rad} rad")

出力:atan2(1.0, 1.0) = 0.7853981633974483 rad

ラジアンと度の変換

math.radians()で度をラジアンに変換し、math.degrees()でラジアンを度に変換できます。

import math
degrees = 90
radians = math.radians(degrees)
print(f"{degrees} degrees = {radians} radians")
radians = math.pi / 2
degrees = math.degrees(radians)
print(f"{radians} radians = {degrees} degrees")

出力: 90 degrees = 1.5707963267948966 radians 1.5707963267948966 radians = 90.0 degrees

その他の三角関数

mathモジュールには、sinh, cosh, tanhなどの双曲線関数も含まれています。

import math
x = 1.0
sinh_x = math.sinh(x)
cosh_x = math.cosh(x)
tanh_x = math.tanh(x)
print(f"sinh({x}) = {sinh_x}")
print(f"cosh({x}) = {cosh_x}")
print(f"tanh({x}) = {tanh_x}")

出力: sinh(1.0) = 1.1752011936438014 cosh(1.0) = 1.5430806348152437 tanh(1.0) = 0.7615941559557649

注意点

三角関数の計算では、角度をラジアンで指定する必要があることに注意してください。度をラジアンに変換する必要がある場合は、math.radians()を使用してください。また、引数の値によっては、オーバーフローやエラーが発生する可能性があります。

  • 引数の値の範囲に注意する
  • オーバーフローやエラーが発生する可能性がある場合は、適切なエラー処理を行う

関連記事