math
--- 数学関数¶
このモジュールは、 C 標準で定義された数学関数へのアクセスを提供します。
これらの関数で複素数を使うことはできません。複素数に対応する必要があるならば、 cmath
モジュールにある同じ名前の関数を使ってください。ほとんどのユーザーは複素数を理解するのに必要なだけの数学を勉強したくないので、複素数に対応した関数と対応していない関数の区別がされています。これらの関数では複素数が利用できないため、引数に複素数を渡されると、複素数の結果が返るのではなく例外が発生します。その結果、どういった理由で例外が送出されたかに早い段階で気づく事ができます。
このモジュールでは次の関数を提供しています。明示的な注記のない限り、戻り値は全て浮動小数点数になります。
数論および数表現の関数¶
- math.ceil(x)¶
Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to
x.__ceil__
, which should return anIntegral
value.
- math.comb(n, k)¶
Return the number of ways to choose k items from n items without repetition and without order.
Evaluates to
n! / (k! * (n - k)!)
whenk <= n
and evaluates to zero whenk > n
.Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of
(1 + x)ⁿ
.Raises
TypeError
if either of the arguments are not integers. RaisesValueError
if either of the arguments are negative.バージョン 3.8 で追加.
- math.copysign(x, y)¶
x の大きさ (絶対値) で y と同じ符号の浮動小数点数を返します。符号付きのゼロをサポートしているプラットフォームでは、
copysign(1.0, -0.0)
は -1.0 を返します。
- math.fabs(x)¶
x の絶対値を返します。
- math.factorial(n)¶
Return n factorial as an integer. Raises
ValueError
if n is not integral or is negative.バージョン 3.9 で非推奨: Accepting floats with integral values (like
5.0
) is deprecated.
- math.floor(x)¶
Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to
x.__floor__
, which should return anIntegral
value.
- math.fmod(x, y)¶
プラットフォームの C ライブラリで定義されている
fmod(x, y)
を返します。 Python のx % y
という式は必ずしも同じ結果を返さないということに注意してください。 C 標準の要求では、fmod()
は除算の結果が x と同じ符号になり、大きさがabs(y)
より小さくなるような整数 n についてはfmod(x, y)
が厳密に (数学的に、つまり無限の精度で)x - n*y
と等価であるよう求めています。 Python のx % y
は、 y と同じ符号の結果を返し、浮動小数点の引数に対して厳密な解を出せないことがあります。例えば、fmod(-1e-100, 1e100)
は-1e-100
ですが、 Python の-1e-100 % 1e100
は1e100-1e-100
になり、浮動小数点型で厳密に表現できず、ややこしいことに1e100
に丸められます。このため、一般には浮動小数点の場合には関数fmod()
、整数の場合にはx % y
を使う方がよいでしょう。
- math.frexp(x)¶
x の仮数と指数を
(m, e)
のペアとして返します。m はfloat型で、e は厳密にx == m * 2**e
であるような整数型です。x がゼロの場合は、(0.0, 0)
を返し、それ以外の場合は、0.5 <= abs(m) < 1
を返します。これは浮動小数点型の内部表現を可搬性を保ったまま "分解 (pick apart)" するためです。
- math.fsum(iterable)¶
iterable 中の値の浮動小数点数の正確な和を返します。複数の部分和を追跡することで精度のロスを防ぎます:
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 0.9999999999999999 >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) 1.0
アルゴリズムの正確性は、 IEEE-754 演算の保証と、丸めモードが偶数丸め (half-even) である典型的な場合に依存します。Windows 以外のいくつかのビルドでは、下層の C ライブラリが拡張精度の加算を行い、時々計算途中の和を double 型へ丸めてしまうため、最下位ビットが消失することがあります。
より詳細な議論と代替となる二つのアプローチについては、ASPN cookbook recipes for accurate floating point summation をご覧下さい。
- math.gcd(*integers)¶
Return the greatest common divisor of the specified integer arguments. If any of the arguments is nonzero, then the returned value is the largest positive integer that is a divisor of all arguments. If all arguments are zero, then the returned value is
0
.gcd()
without arguments returns0
.バージョン 3.5 で追加.
バージョン 3.9 で変更: Added support for an arbitrary number of arguments. Formerly, only two arguments were supported.
- math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)¶
値 a と b が互いに近い場合
True
を、そうでない場合はFalse
を返します。2値が近いと見なされるかどうかは与えられた絶対または相対許容差により決定されます。
rel_tol は相対許容差、すなわち a と b の絶対値の大きい方に対する a と b の許容される最大の差です。 例えば許容差を 5% に設定する場合
rel_tol=0.05
を渡します。 デフォルトの許容差は1e-09
で、2値が9桁同じことを保証します。 rel_tol は0より大きくなければなりません。abs_tol は最小の絶対許容差です。0に近い値を比較するのに有用です。abs_tol は0以上でなければなりません。
エラーが起こらなければ結果は
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
です。IEEE 754 特殊値
NaN
、inf
、-inf
は IEEE の規則に従って処理されます。 具体的には、NaN
は自身を含めたあらゆる値に近いとは見なされません。inf
と-inf
は自身とのみ近いと見なされます。バージョン 3.5 で追加.
参考
PEP 485 -- A function for testing approximate equality
- math.isfinite(x)¶
x が無限でも NaN でもない場合に
True
を返します。それ以外の時にはFalse
を返します。 (注意:0.0
は有限数と扱われます。)バージョン 3.2 で追加.
- math.isinf(x)¶
x が正ないし負の無限数ならば
True
を返します。それ以外の時にはFalse
を返します。
- math.isnan(x)¶
x がNaN (not a number、非数) の時に
True
を返します。それ以外の場合にはFalse
を返します。
- math.isqrt(n)¶
Return the integer square root of the nonnegative integer n. This is the floor of the exact square root of n, or equivalently the greatest integer a such that a² ≤ n.
For some applications, it may be more convenient to have the least integer a such that n ≤ a², or in other words the ceiling of the exact square root of n. For positive n, this can be computed using
a = 1 + isqrt(n - 1)
.バージョン 3.8 で追加.
- math.lcm(*integers)¶
Return the least common multiple of the specified integer arguments. If all arguments are nonzero, then the returned value is the smallest positive integer that is a multiple of all arguments. If any of the arguments is zero, then the returned value is
0
.lcm()
without arguments returns1
.バージョン 3.9 で追加.
- math.modf(x)¶
x の小数部分と整数部分を返します。両方の結果は x の符号を受け継ぎます。整数部はfloat型で返されます。
- math.nextafter(x, y)¶
Return the next floating-point value after x towards y.
If x is equal to y, return y.
例:
math.nextafter(x, math.inf)
goes up: towards positive infinity.math.nextafter(x, -math.inf)
goes down: towards minus infinity.math.nextafter(x, 0.0)
goes towards zero.math.nextafter(x, math.copysign(math.inf, x))
goes away from zero.
math.ulp()
を参照してください。バージョン 3.9 で追加.
- math.perm(n, k=None)¶
Return the number of ways to choose k items from n items without repetition and with order.
Evaluates to
n! / (n - k)!
whenk <= n
and evaluates to zero whenk > n
.If k is not specified or is None, then k defaults to n and the function returns
n!
.Raises
TypeError
if either of the arguments are not integers. RaisesValueError
if either of the arguments are negative.バージョン 3.8 で追加.
- math.prod(iterable, *, start=1)¶
Calculate the product of all the elements in the input iterable. The default start value for the product is
1
.When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types.
バージョン 3.8 で追加.
- math.remainder(x, y)¶
IEEE 754 標準方式の x を y で割った剰余を返します。 有限な x と有限な y では、分数
x / y
の厳密な値に最も近い整数をn
として、x - n*y
がこの返り値となります。x / y
が隣り合う 2 つの整数のちょうど真ん中だった場合は、最も近い 偶数 がn
として使われます。 従って、剰余r = remainder(x, y)
は常にabs(r) <= 0.5 * abs(y)
を満たします。特殊なケースについては IEEE 754 に従います: 任意の有限な x に対する
remainder(x, math.inf)
、および任意の非 NaN の x に対するremainder(x, 0)
とremainder(math.inf, x)
はValueError
を送出します。 剰余演算の結果がゼロの場合、そのゼロは x と同じ符号を持ちます。IEEE 754 の二進浮動小数点数を使用しているプラットフォームでは、この演算の結果は常に厳密に表現可能です。丸め誤差は発生しません。
バージョン 3.7 で追加.
- math.trunc(x)¶
Return x with the fractional part removed, leaving the integer part. This rounds toward 0:
trunc()
is equivalent tofloor()
for positive x, and equivalent toceil()
for negative x. If x is not a float, delegates tox.__trunc__
, which should return anIntegral
value.
- math.ulp(x)¶
Return the value of the least significant bit of the float x:
If x is a NaN (not a number), return x.
If x is negative, return
ulp(-x)
.If x is a positive infinity, return x.
If x is equal to zero, return the smallest positive denormalized representable float (smaller than the minimum positive normalized float,
sys.float_info.min
).If x is equal to the largest positive representable float, return the value of the least significant bit of x, such that the first float smaller than x is
x - ulp(x)
.Otherwise (x is a positive finite number), return the value of the least significant bit of x, such that the first float bigger than x is
x + ulp(x)
.
ULP stands for "Unit in the Last Place".
See also
math.nextafter()
andsys.float_info.epsilon
.バージョン 3.9 で追加.
frexp()
と modf()
は C のものとは異なった呼び出し/返しパターンを持っていることに注意してください。引数を1つだけ受け取り、1組のペアになった値を返すので、2つ目の戻り値を '出力用の引数' 経由で返したりはしません (Python には出力用の引数はありません)。
ceil()
、 floor()
、および modf()
関数については、非常に大きな浮動小数点数が 全て 整数そのものになるということに注意してください。通常、Python の浮動小数点型は 53 ビット以上の精度をもたない (プラットフォームにおける C double 型と同じ) ので、結果的に abs(x) >= 2**52
であるような浮動小数点型 x は小数部分を持たなくなるのです。
指数関数と対数関数¶
- math.cbrt(x)¶
Return the cube root of x.
バージョン 3.11 で追加.
- math.exp(x)¶
e = 2.718281... を自然対数の底として、 e の x 乗を返します。 この値は、通常は
math.e ** x
やpow(math.e, x)
よりも精度が高いです。
- math.exp2(x)¶
Return 2 raised to the power x.
バージョン 3.11 で追加.
- math.expm1(x)¶
e の x 乗から 1 を引いた値を返します。 ここでの e は自然対数の底です。 小さい浮動小数点数の x において、減算
exp(x) - 1
は 桁落ち が発生します。expm1()
関数は、この量を最大精度で計算する方法を提供します。>>> from math import exp, expm1 >>> exp(1e-5) - 1 # gives result accurate to 11 places 1.0000050000069649e-05 >>> expm1(1e-5) # result accurate to full precision 1.0000050000166668e-05
バージョン 3.2 で追加.
- math.log(x[, base])¶
引数が1つの場合、x の (e を底とする)自然対数を返します。
引数が2つの場合、
log(x)/log(base)
として求められる base を底とした x の対数を返します。
- math.log1p(x)¶
1+x の自然対数(つまり底 e の対数)を返します。結果はゼロに近い x に対して正確になるような方法で計算されます。
- math.log2(x)¶
2を底とする x の対数を返します。この関数は、一般に
log(x, 2)
よりも正確な値を返します。バージョン 3.3 で追加.
参考
int.bit_length()
は、その整数を二進法で表すのに何ビット必要かを返す関数です。符号と先頭のゼロは無視されます。
- math.log10(x)¶
x の10を底とした対数(常用対数)を返します。この関数は通常、
log(x, 10)
よりも高精度です。
- math.pow(x, y)¶
Return
x
raised to the powery
. Exceptional cases follow the IEEE 754 standard as far as possible. In particular,pow(1.0, x)
andpow(x, 0.0)
always return1.0
, even whenx
is a zero or a NaN. If bothx
andy
are finite,x
is negative, andy
is not an integer thenpow(x, y)
is undefined, and raisesValueError
.組み込みの
**
演算子と違って、math.pow()
は両方の引数をfloat
型に変換します。正確な整数の冪乗を計算するには**
もしくは組み込みのpow()
関数を使ってください。バージョン 3.11 で変更: The special cases
pow(0.0, -inf)
andpow(-0.0, -inf)
were changed to returninf
instead of raisingValueError
, for consistency with IEEE 754.
- math.sqrt(x)¶
x の平方根を返します。
三角関数¶
- math.acos(x)¶
Return the arc cosine of x, in radians. The result is between
0
andpi
.
- math.asin(x)¶
Return the arc sine of x, in radians. The result is between
-pi/2
andpi/2
.
- math.atan(x)¶
Return the arc tangent of x, in radians. The result is between
-pi/2
andpi/2
.
- math.atan2(y, x)¶
atan(y / x)
を、ラジアンで返します。戻り値は-pi
からpi
の間になります。この角度は、極座標平面において原点から(x, y)
へのベクトルが X 軸の正の方向となす角です。atan2()
のポイントは、両方の入力の符号が既知であるために、位相角の正しい象限を計算できることにあります。例えば、atan(1)
とatan2(1, 1)
はいずれもpi/4
ですが、atan2(-1, -1)
は-3*pi/4
になります。
- math.cos(x)¶
x ラジアンの余弦を返します。
- math.dist(p, q)¶
Return the Euclidean distance between two points p and q, each given as a sequence (or iterable) of coordinates. The two points must have the same dimension.
およそ次と等価です:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
バージョン 3.8 で追加.
- math.hypot(*coordinates)¶
Return the Euclidean norm,
sqrt(sum(x**2 for x in coordinates))
. This is the length of the vector from the origin to the point given by the coordinates.For a two dimensional point
(x, y)
, this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem,sqrt(x*x + y*y)
.バージョン 3.8 で変更: Added support for n-dimensional points. Formerly, only the two dimensional case was supported.
バージョン 3.10 で変更: Improved the algorithm's accuracy so that the maximum error is under 1 ulp (unit in the last place). More typically, the result is almost always correctly rounded to within 1/2 ulp.
- math.sin(x)¶
x ラジアンの正弦を返します。
- math.tan(x)¶
x ラジアンの正接を返します。
角度変換¶
- math.degrees(x)¶
角 x をラジアンから度に変換します。
- math.radians(x)¶
角 x を度からラジアンに変換します。
双曲線関数¶
双曲線関数 は円ではなく双曲線を元にした三角関数のようなものです。
- math.acosh(x)¶
x の逆双曲線余弦を返します。
- math.asinh(x)¶
x の逆双曲線正弦を返します。
- math.atanh(x)¶
x の逆双曲線正接を返します。
- math.cosh(x)¶
x の双曲線余弦を返します。
- math.sinh(x)¶
x の双曲線正弦を返します。
- math.tanh(x)¶
x の双曲線正接を返します。
特殊関数¶
- math.erf(x)¶
x の 誤差関数 を返します。
The
erf()
function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:def phi(x): 'Cumulative distribution function for the standard normal distribution' return (1.0 + erf(x / sqrt(2.0))) / 2.0
バージョン 3.2 で追加.
- math.erfc(x)¶
x の相補誤差関数を返します。相補誤差関数 は
1.0 - erf(x)
と定義されます。この関数は、1との引き算では 桁落ち をするような大きな x に対し使われます。バージョン 3.2 で追加.
- math.lgamma(x)¶
x のガンマ関数の絶対値の自然対数を返します。
バージョン 3.2 で追加.
定数¶
- math.pi¶
利用可能なだけの精度の数学定数 π = 3.141592... (円周率)。
- math.e¶
利用可能なだけの精度の数学定数 e = 2.718281... (自然対数の底)。
- math.tau¶
利用可能なだけの精度の数学定数 τ = 6.283185... です。 タウは 2π に等しい円定数で、円周と半径の比です。 タウについて学ぶには Vi Hart のビデオ Pi is (still) Wrong をチェックして、パイを二倍食べて Tau day を祝い始めましょう!
バージョン 3.6 で追加.
- math.inf¶
浮動小数の正の無限大です。(負の無限大には
-math.inf
を使います。)float('inf')
の出力と等価です。バージョン 3.5 で追加.
- math.nan¶
A floating-point "not a number" (NaN) value. Equivalent to the output of
float('nan')
. Due to the requirements of the IEEE-754 standard,math.nan
andfloat('nan')
are not considered to equal to any other numeric value, including themselves. To check whether a number is a NaN, use theisnan()
function to test for NaNs instead ofis
or==
. Example:>>> import math >>> math.nan == math.nan False >>> float('nan') == float('nan') False >>> math.isnan(math.nan) True >>> math.isnan(float('nan')) True
バージョン 3.11 で変更: It is now always available.
バージョン 3.5 で追加.
CPython 実装の詳細: math
モジュールは、ほとんどが実行プラットフォームにおける C 言語の数学ライブラリ関数に対する薄いラッパでできています。
例外時の挙動は、適切である限り C99 標準の Annex F に従います。
現在の実装では、sqrt(-1.0)
や log(0.0)
といった (C99 Annex F で不正な演算やゼロ除算を通知することが推奨されている) 不正な操作に対して ValueError
を送出し、(例えば exp(1000.0)
のような) 演算結果がオーバーフローする場合には OverflowError
を送出します。
上記の関数群は、1つ以上の引数が NaN であった場合を除いて NaN を返しません。
引数に NaN が与えられた場合は、殆どの関数は NaN を返しますが、 (C99 Annex F に従って) 別の動作をする場合があります。
例えば、 pow(float('nan'), 0.0)
や hypot(float('nan'), float('inf'))
といった場合です。
訳注: 例外が発生せずに結果が返ると、計算結果がおかしくなった原因が複素数を渡したためだということに気づくのが遅れる可能性があります。
Python は signaling NaN と quiet NaN を区別せず、signaling NaN に対する挙動は未定義とされていることに注意してください。典型的な挙動は、全ての NaN を quiet NaN として扱うことです。
参考
cmath
モジュールこれらの多くの関数の複素数版。