math.pi / math.e / math.log() / math.sin()
| 対応: | Python 2(2000) |
|---|
『math』モジュールが提供する数学定数・対数・三角関数です。科学計算や角度の変換などに使用します。
構文
import math # 数学定数 math.pi # 円周率 π(約3.141592653589793) math.e # 自然対数の底 e(約2.718281828459045) # 対数を計算する math.log(x) # 自然対数(底 e) math.log(x, 底) # 指定した底の対数 math.log2(x) # 底2の対数 math.log10(x) # 底10の対数 # 三角関数(引数はラジアン) math.sin(x) math.cos(x) math.tan(x) # 角度とラジアンの変換 math.radians(度) # 度 → ラジアン math.degrees(ラジアン) # ラジアン → 度
定数・関数一覧
| 定数・関数 | 概要 |
|---|---|
| math.pi | 円周率 π(3.141592653589793)です。円の面積や三角関数の計算に使います。 |
| math.e | 自然対数の底 e(2.718281828459045)です。指数関数・対数計算の基底です。 |
| math.log(x) | xの自然対数(底 e)を返します。xが0以下の場合は『ValueError』が発生します。 |
| math.log(x, 底) | xの指定した底の対数を返します。 |
| math.log2(x) | xの底2の対数を返します。ビット数の計算などに使います。 |
| math.log10(x) | xの底10の対数(常用対数)を返します。 |
| math.sin(x) | xのサイン(正弦)を返します。引数はラジアンで指定します。 |
| math.cos(x) | xのコサイン(余弦)を返します。引数はラジアンで指定します。 |
| math.tan(x) | xのタンジェント(正接)を返します。引数はラジアンで指定します。 |
| math.radians(度) | 度数法の角度をラジアンに変換します。 |
| math.degrees(ラジアン) | ラジアンを度数法の角度に変換します。 |
サンプルコード
math_pi_log_1.py
import math
# 数学定数を使う
print(math.pi)
print(math.e)
# 円の面積を計算する
radius = 5
area = math.pi * radius ** 2
print(f'面積: {area:.2f}')
実行すると次のように出力されます。
python3 math_pi_log_1.py 3.141592653589793 2.718281828459045 面積: 78.54
math_pi_log_2.py
import math # 対数を計算する print(math.log(math.e)) print(math.log(100, 10)) print(math.log2(1024)) print(math.log10(1000))
実行すると次のように出力されます。
python3 math_pi_log_2.py 1.0 2.0 10.0 3.0
math_pi_log_3.py
import math # 三角関数はラジアンを引数に取る angle_deg = 30 angle_rad = math.radians(angle_deg) print(math.sin(angle_rad)) print(math.cos(angle_rad)) # math.pi を使ってラジアンを指定することもできる print(math.sin(math.pi / 6)) print(math.cos(0)) print(math.cos(math.pi)) # ラジアンから度に変換する print(math.degrees(math.pi)) print(math.degrees(math.pi / 2))
実行すると次のように出力されます。
python3 math_pi_log_3.py 0.49999999999999994 0.8660254037844387 0.49999999999999994 1.0 -1.0 180.0 90.0
よくあるミス
よくあるミス1: 三角関数に度数をそのまま渡す
Pythonの三角関数はラジアン単位で引数を受け取ります。度数をそのまま渡すと意図しない結果になります。『math.radians()』で変換してから渡します。
mistake1_ng.py
import math print(math.sin(90))
実行すると次のように出力されます。
python3 mistake1_ng.py 0.8939966636005579
mistake1_ok.py
import math print(math.sin(math.radians(90)))
実行すると次のように出力されます。
python3 mistake1_ok.py 1.0
よくあるミス2: log() にゼロや負の数を渡す
『math.log()』の引数が0以下の場合は『ValueError』が発生します。対数の定義域は正の実数のみです。入力値を事前に確認するか、例外処理を組み合わせて使います。
mistake2_ng.py
import math print(math.log(0))
実行すると次のように出力されます。
python3 mistake2_ng.py ValueError: math domain error
mistake2_ok.py
import math
value = 0
if value > 0:
print(math.log(value))
else:
print("対数を計算できません(0以下の値)")
実行すると次のように出力されます。
python3 mistake2_ok.py 対数を計算できません(0以下の値)
概要
『math.pi』や『math.e』はPythonが内部的に保持する高精度の数学定数です。これらは変数として直接アクセスでき、関数呼び出しのカッコは不要です。
Pythonの三角関数はすべてラジアン単位で角度を受け取ります。度数法(0°〜360°)で考える場合は『math.radians()』で変換してから渡してください。『math.sin(90)』は90°のサインではなく90ラジアンのサインになります。度をそのまま渡すと正しい結果が得られないため変換が必要になります。
平方根・切り上げ・切り捨ては『math.sqrt() / math.ceil() / math.floor()』を参照してください。
記事の間違いや著作権の侵害等ございましたらお手数ですがこちらまでご連絡頂ければ幸いです。