Pythonで指数関数・対数関数を計算(exp, log, log10, log2)
Pythonの数学関数の標準モジュールmath
を使うと、指数関数および対数関数(自然対数、常用対数、二進対数)の計算ができる。
ここでは、
- 自然対数の底(ネイピア数):
math.e
- べき乗:
**
演算子,pow()
,math.pow()
- 平方根(ルート):
math.sqrt()
- 指数関数(自然指数関数):
math.exp()
- 対数関数:
math.log()
,math.log10()
,math.log2()
について、サンプルコードとともに説明する。
自然対数の底(ネイピア数): math.e
自然対数の底(ネイピア数)はmath
モジュールの中で定数として用意されている。math.e
で表す。
import math
print(math.e)
# 2.718281828459045
べき乗: **演算子, pow(), math.pow()
べき乗を計算するには、**
演算子, 組み込み関数pow()
, math.pow()
のいずれかを使う。
x
のy
乗は、それぞれ、x**y
, pow(x, y)
, math.pow(x, y)
で得られる。
print(2**4)
# 16
print(pow(2, 4))
# 16
print(math.pow(2, 4))
# 16.0
math.pow()
は引数を浮動小数点float
型に変換するのに対して、Pythonの組み込み関数pow()
では各型それぞれで定義された__pow()__
を使って処理する。
例えば、pow()
では引数に複素数complex
型を指定できるが、math.pow()
ではcomplex
型からfloat
型に変換できないため、エラーとなる。
print(pow(1 + 1j, 2))
# 2j
# print(math.pow(1 + 1j, 2))
# TypeError: can't convert complex to float
また、Pythonの組み込み関数pow()
では第三引数を指定することができ、pow(x, y, z)
はx
のy
乗に対するz
の剰余(あまり)を返す。pow(x, y) % z
と同じ計算だが、pow(x, y, z)
のほうが効率よく計算される。
print(pow(2, 4, 5))
# 1
平方根(ルート): math.sqrt()
平方根(ルート)は、べき乗演算子**
を使って**0.5
とするか、math.sqrt()
を使う。
print(2**0.5)
# 1.4142135623730951
print(math.sqrt(2))
# 1.4142135623730951
print(2**0.5 == math.sqrt(2))
# True
math.pow()
と同じくmath.sqrt()
では引数を浮動小数点float
型に変換して処理するため、float
型に変換できない型を指定するとエラーTypeError
になる。
print((-3 + 4j)**0.5)
# (1.0000000000000002+2j)
# print(math.sqrt(-3 + 4j))
# TypeError: can't convert complex to float
また、math.sqrt()
は負の値も処理できずエラーValueError
となる。
print((-1)**0.5)
# (6.123233995736766e-17+1j)
# print(math.sqrt(-1))
# ValueError: math domain error
なお、複素数を扱う場合、**
演算子を使った例では誤差が生じているが、cmath
モジュールを使うとより正確な値が得られる。
import cmath
print(cmath.sqrt(-3 + 4j))
# (1+2j)
print(cmath.sqrt(-1))
# 1j
指数関数(自然指数関数): math.exp()
自然対数の底(ネイピア数)e
のべき乗を計算するには、math.exp()
を使う。
math.exp(x)
はe
のx
乗を返す。math.exp(x)
はmath.e ** x
と等価でなく、math.exp(x)
のほうがより正確な値となる。
print(math.exp(2))
# 7.38905609893065
print(math.exp(2) == math.e**2)
# False
対数関数: math.log(), math.log10(), math.log2()
対数関数を計算するには、math.log()
, math.log10()
, math.log2()
を使う。
math.log(x, y)
はy
を底としたx
の対数を返す。
print(math.log(25, 5))
# 2.0
第二引数を省略すると次に示す自然対数となる。
自然対数
数学ではlog
とかln
で表される自然対数(ネイピア数e
を底とする対数)は、math.log(x)
で計算できる。
print(math.log(math.e))
# 1.0
常用対数
常用対数(10を底とする対数)は、math.log10(x)
で計算できる。math.log(x, 10)
よりも正確な値となる。
print(math.log10(100000))
# 5.0
二進対数
二進対数(2を底とする対数)は、math.log2(x)
で計算できる。math.log(x, 2)
よりも正確な値となる。
print(math.log2(1024))
# 10.0