math --- 数学関数¶
This module provides access to common mathematical functions and constants, including those defined by the C standard.
これらの関数で複素数を使うことはできません。複素数に対応する必要があるならば、 cmath モジュールにある同じ名前の関数を使ってください。ほとんどのユーザーは複素数を理解するのに必要なだけの数学を勉強したくないので、複素数に対応した関数と対応していない関数の区別がされています。これらの関数では複素数が利用できないため、引数に複素数を渡されると、複素数の結果が返るのではなく例外が発生します。その結果、どういった理由で例外が送出されたかに早い段階で気づく事ができます。
このモジュールでは次の関数を提供しています。明示的な注記のない限り、戻り値は全て浮動小数点数になります。
| Number-theoretic functions | |
| Number of ways to choose k items from n items without repetition and without order | |
| n factorial | |
| Greatest common divisor of the integer arguments | |
| Integer square root of a nonnegative integer n | |
| Least common multiple of the integer arguments | |
| Number of ways to choose k items from n items without repetition and with order | |
| Floating point arithmetic | |
| Ceiling of x, the smallest integer greater than or equal to x | |
| Absolute value of x | |
| Floor of x, the largest integer less than or equal to x | |
| Fused multiply-add operation:  | |
| Remainder of division  | |
| Fractional and integer parts of x | |
| Remainder of x with respect to y | |
| Integer part of x | |
| Floating point manipulation functions | |
| Magnitude (absolute value) of x with the sign of y | |
| Mantissa and exponent of x | |
| Check if the values a and b are close to each other | |
| Check if x is neither an infinity nor a NaN | |
| Check if x is a positive or negative infinity | |
| Check if x is a NaN (not a number) | |
| 
 | |
| Floating-point value steps steps after x towards y | |
| Value of the least significant bit of x | |
| Power, exponential and logarithmic functions | |
| Cube root of x | |
| e raised to the power x | |
| 2 raised to the power x | |
| e raised to the power x, minus 1 | |
| Logarithm of x to the given base (e by default) | |
| Natural logarithm of 1+x (base e) | |
| Base-2 logarithm of x | |
| Base-10 logarithm of x | |
| x raised to the power y | |
| Square root of x | |
| Summation and product functions | |
| Euclidean distance between two points p and q given as an iterable of coordinates | |
| Sum of values in the input iterable | |
| Euclidean norm of an iterable of coordinates | |
| Product of elements in the input iterable with a start value | |
| Sum of products from two iterables p and q | |
| Angular conversion | |
| Convert angle x from radians to degrees | |
| Convert angle x from degrees to radians | |
| Trigonometric functions | |
| Arc cosine of x | |
| Arc sine of x | |
| Arc tangent of x | |
| 
 | |
| Cosine of x | |
| Sine of x | |
| Tangent of x | |
| Hyperbolic functions | |
| Inverse hyperbolic cosine of x | |
| Inverse hyperbolic sine of x | |
| Inverse hyperbolic tangent of x | |
| Hyperbolic cosine of x | |
| Hyperbolic sine of x | |
| Hyperbolic tangent of x | |
| Special functions | |
| Error function at x | |
| Gamma function at x | |
| Natural logarithm of the absolute value of the Gamma function at x | |
| Constants | |
| π = 3.141592... | |
| e = 2.718281... | |
| τ = 2π = 6.283185... | |
| Positive infinity | |
| "Not a number" (NaN) | |
Number-theoretic functions¶
- math.comb(n, k)¶
- n 個の中から k 個を重複無く順序をつけずに選ぶ方法の数を返します。 - k <= nのとき- n! / (k! * (n - k)!)と評価し、- k > nのとき 0 と評価します。- これは - (1 + x)ⁿの多項式展開における第 k 項の係数と等しいので、二項係数とも呼ばれます。- いずれかの引数が整数でないなら - TypeErrorを送出します。いずれかの引数が負であれば- ValueErrorを送出します。- Added in version 3.8. 
- math.factorial(n)¶
- Return factorial of the nonnegative integer n. - バージョン 3.10 で変更: Floats with integral values (like - 5.0) are no longer accepted.
- math.gcd(*integers)¶
- 指定された整数引数の最大公約数を返します。0 でない引数があれば、返される値は全ての引数の約数である最大の正の整数です。全ての引数が 0 なら、返される値は - 0です。引数の無い- gcd()は- 0を返します。- Added in version 3.5. - バージョン 3.9 で変更: 任意の数の引数のサポートが追加されました。以前は、二つの引数のみがサポートされていました。 
- math.isqrt(n)¶
- 非負整数 n の整数平方根を返します。これは n の正確な平方根の床であり、 a² ≤ n を満たす最大の整数 a と等価です。 - 少し応用すれば、n ≤ a² を満たす最小の整数 a 、言い換えれば n の正確な平方根の天井を効率的に得られます。正の n に対して、これは - a = 1 + isqrt(n - 1)を使って計算できます。- Added in version 3.8. 
- math.lcm(*integers)¶
- 指定された整数引数の最小公倍数を返します。全ての引数が 0 でなければ、返される値は全ての引数の倍数である最小の正の整数です。引数に 0 があれば、返される値は - 0です。引数の無い- lcm()は- 1を返します。- Added in version 3.9. 
- math.perm(n, k=None)¶
- n 個の中から k 個を重複無く順序をつけて選ぶ方法の数を返します。 - k <= nのとき- n! / (n - k)!と評価し、- k > nのとき 0 と評価します。- If k is not specified or is - None, then k defaults to n and the function returns- n!.- いずれかの引数が整数でないなら - TypeErrorを送出します。いずれかの引数が負であれば- ValueErrorを送出します。- Added in version 3.8. 
Floating point arithmetic¶
- math.ceil(x)¶
- x の「天井」 (x 以上の最小の整数) を返します。 x が浮動小数点数でなければ、内部的に - x.__ceil__が実行され、- Integral値が返されます。
- math.fabs(x)¶
- x の絶対値を返します。 
- math.floor(x)¶
- x の「床」 (x 以下の最大の整数) を返します。 x が浮動小数点数でなければ、内部的に - x.__floor__が実行され、- Integral値が返されます。
- math.fma(x, y, z)¶
- Fused multiply-add operation. Return - (x * y) + z, computed as though with infinite precision and range followed by a single round to the- floatformat. This operation often provides better accuracy than the direct expression- (x * y) + z.- This function follows the specification of the fusedMultiplyAdd operation described in the IEEE 754 standard. The standard leaves one case implementation-defined, namely the result of - fma(0, inf, nan)and- fma(inf, 0, nan). In these cases,- math.fmareturns a NaN, and does not raise any exception.- Added in version 3.13. 
- math.fmod(x, y)¶
- Return the floating-point remainder of - x / y, as defined by the platform C library function- fmod(x, y). Note that the Python expression- x % ymay not return the same result. The intent of the C standard is that- fmod(x, y)be exactly (mathematically; to infinite precision) equal to- x - n*yfor some integer n such that the result has the same sign as x and magnitude less than- abs(y). Python's- x % yreturns a result with the sign of y instead, and may not be exactly computable for float arguments. For example,- fmod(-1e-100, 1e100)is- -1e-100, but the result of Python's- -1e-100 % 1e100is- 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising- 1e100. For this reason, function- fmod()is generally preferred when working with floats, while Python's- x % yis preferred when working with integers.
- math.modf(x)¶
- x の小数部分と整数部分を返します。両方の結果は x の符号を受け継ぎます。整数部はfloat型で返されます。 - Note that - modf()has a different call/return pattern than its C equivalents: it takes a single argument and return a pair of values, rather than returning its second return value through an 'output parameter' (there is no such thing in Python).
- 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 と同じ符号を持ちます。- On platforms using IEEE 754 binary floating point, the result of this operation is always exactly representable: no rounding error is introduced. - Added in version 3.7. 
- math.trunc(x)¶
- x の小数部を取り除き、残った整数部を返します。これは 0 に向かって丸められます: - trunc()は正の x に対しては- floor()に等しく、負の x に対しては- ceil()に等しいです。x が浮動小数点数でなければ、内部的に- x.__trunc__が実行され、- Integral値が返されます。
ceil() 、 floor() 、および modf() 関数については、非常に大きな浮動小数点数が 全て 整数そのものになるということに注意してください。通常、Python の浮動小数点型は 53 ビット以上の精度をもたない (プラットフォームにおける C double 型と同じ) ので、結果的に abs(x) >= 2**52 であるような浮動小数点型 x は小数部分を持たなくなるのです。
Floating point manipulation functions¶
- math.copysign(x, y)¶
- x の大きさ (絶対値) で y と同じ符号の浮動小数点数を返します。符号付きのゼロをサポートしているプラットフォームでは、 - copysign(1.0, -0.0)は -1.0 を返します。
- math.frexp(x)¶
- x の仮数と指数を - (m, e)のペアとして返します。m はfloat型で、e は厳密に- x == m * 2**eであるような整数型です。x がゼロの場合は、- (0.0, 0)を返し、それ以外の場合は、- 0.5 <= abs(m) < 1です。これは浮動小数点型の内部表現を可搬性を保ったまま "分解 (pick apart)" するために使われます。- Note that - frexp()has a different call/return pattern than its C equivalents: it takes a single argument and return a pair of values, rather than returning its second return value through an 'output parameter' (there is no such thing in Python).
- math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)¶
- 値 a と b が互いに近い場合 - Trueを、そうでない場合は- Falseを返します。- Whether or not two values are considered close is determined according to given absolute and relative tolerances. If no errors occur, the result will be: - abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol).- rel_tol is the relative tolerance -- it is the maximum allowed difference between a and b, relative to the larger absolute value of a or b. For example, to set a tolerance of 5%, pass - rel_tol=0.05. The default tolerance is- 1e-09, which assures that the two values are the same within about 9 decimal digits. rel_tol must be nonnegative and less than- 1.0.- abs_tol is the absolute tolerance; it defaults to - 0.0and it must be nonnegative. When comparing- xto- 0.0,- isclose(x, 0)is computed as- abs(x) <= rel_tol * abs(x), which is- Falsefor any nonzero- xand rel_tol less than- 1.0. So add an appropriate positive abs_tol argument to the call.- IEEE 754 特殊値 - NaN、- inf、- -infは IEEE の規則に従って処理されます。 具体的には、- NaNは自身を含めたあらゆる値に近いとは見なされません。- infと- -infは自身とのみ近いと見なされます。- Added in version 3.5. - 参考 - PEP 485 -- A function for testing approximate equality 
- math.isfinite(x)¶
- x が無限でも NaN でもない場合に - Trueを返します。それ以外の時には- Falseを返します。 (注意:- 0.0は有限数と扱われます。)- Added in version 3.2. 
- math.isinf(x)¶
- x が正ないし負の無限数ならば - Trueを返します。それ以外の時には- Falseを返します。
- math.isnan(x)¶
- x がNaN (not a number、非数) の時に - Trueを返します。それ以外の場合には- Falseを返します。
- math.nextafter(x, y, steps=1)¶
- Return the floating-point value steps steps after x towards y. - If x is equal to y, return y, unless steps is zero. - 例: - 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)は 0 に近づきます。
- math.nextafter(x, math.copysign(math.inf, x))は 0 から遠ざかります。
 - math.ulp()を参照してください。- Added in version 3.9. - バージョン 3.12 で変更: Added the steps argument. 
- math.ulp(x)¶
- 浮動小数点数 x の最下位ビットの値を返します: - x が NaN (非数) なら、x を返します。 
- x が負なら、 - ulp(-x)を返します。
- x が正の無限大なら、x を返します。 
- x が 0 に等しければ、(最小の正の 正規化 浮動小数点数 - sys.float_info.minよりも小さい) 最小の正の表現可能な 非正規化 浮動小数点数を返します。
- x が表現可能な最大の正の浮動小数点数に等しいなら、x より小さい最初の浮動小数点数が - x - ulp(x)であるような、x の最下位ビットの値を返します。
- それ以外 (x が正の有限な数) なら、x より大きい最初の浮動小数点数が - x + ulp(x)であるような、x の最下位ビットの値を返します。
 - ULP は "Unit in the Last Place" の略です。 - math.nextafter()および- sys.float_info.epsilonも参照してください。- Added in version 3.9. 
Power, exponential and logarithmic functions¶
- math.cbrt(x)¶
- x の立方根を返します。 - Added in version 3.11. 
- math.exp(x)¶
- e = 2.718281... を自然対数の底として、 e の x 乗を返します。 この値は、通常は - math.e ** xや- pow(math.e, x)よりも精度が高いです。
- math.exp2(x)¶
- 2 の x 乗を返します。 - Added in version 3.11. 
- math.expm1(x)¶
- Return e raised to the power x, minus 1. Here e is the base of natural logarithms. For small floats x, the subtraction in - exp(x) - 1can result in a significant loss of precision; the- expm1()function provides a way to compute this quantity to full precision:- >>> 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 - Added in version 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)よりも正確な値を返します。- Added in version 3.3. - 参考 - int.bit_length()は、その整数を二進法で表すのに何ビット必要かを返す関数です。符号と先頭のゼロは無視されます。
- math.log10(x)¶
- x の10を底とした対数(常用対数)を返します。この関数は通常、 - log(x, 10)よりも高精度です。
- math.pow(x, y)¶
- Return x raised to the power y. Exceptional cases follow the IEEE 754 standard as far as possible. In particular, - pow(1.0, x)and- pow(x, 0.0)always return- 1.0, even when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer then- pow(x, y)is undefined, and raises- ValueError.- 組み込みの - **演算子と違って、- math.pow()は両方の引数を- float型に変換します。正確な整数の冪乗を計算するには- **もしくは組み込みの- pow()関数を使ってください。- バージョン 3.11 で変更: IEEE 754 との一貫性のため、特殊な例である - pow(0.0, -inf)および- pow(-0.0, -inf)は- ValueErrorを送出する代わりに- infを返すように変更されました。
- math.sqrt(x)¶
- x の平方根を返します。 
Summation and product functions¶
- math.dist(p, q)¶
- それぞれ座標のシーケンス (またはイテラブル) として与えられる点 p と q の間のユークリッド距離を返します。二点の次元は同じでなければなりません。 - およそ次と等価です: - sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) - Added in version 3.8. 
- math.fsum(iterable)¶
- Return an accurate floating-point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums. - アルゴリズムの正確性は、 IEEE-754 演算の保証と、丸めモードが偶数丸め (half-even) である典型的な場合に依存します。Windows 以外のいくつかのビルドでは、下層の C ライブラリが拡張精度の加算を行い、時々計算途中の和を double 型へ丸めてしまうため、最下位ビットが消失することがあります。 - For further discussion and two alternative approaches, see the ASPN cookbook recipes for accurate floating-point summation. 
- math.hypot(*coordinates)¶
- ユークリッドノルム - sqrt(sum(x**2 for x in coordinates))を返します。これは原点から座標で与えられる点までのベクトルの長さです。- 二次元の点 - (x, y)では、これは直角三角形の斜辺をピタゴラスの定理- sqrt(x*x + y*y)を用いて計算することと等価です。- バージョン 3.8 で変更: n 次元の点のサポートが追加されました。以前は、二次元の場合しかサポートされていませんでした。 - バージョン 3.10 で変更: アルゴリズムの精度を改良し、最大の誤差が 1 ulp (最終桁単位) 未満になりました。より一般的には、結果はほとんどの場合に 1/2 ulp 以内に正しく丸められます。 
- math.prod(iterable, *, start=1)¶
- 入力 iterable の全ての要素の積を計算します。積のデフォルト start 値は - 1です。- イテラブルが空のとき、初期値を返します。この関数は特に数値に使うことを意図されており、非数値を受け付けないことがあります。 - Added in version 3.8. 
- math.sumprod(p, q)¶
- Return the sum of products of values from two iterables p and q. - Raises - ValueErrorif the inputs do not have the same length.- およそ次と等価です: - sum(map(operator.mul, p, q, strict=True)) - For float and mixed int/float inputs, the intermediate products and sums are computed with extended precision. - Added in version 3.12. 
角度変換¶
- math.degrees(x)¶
- 角 x をラジアンから度に変換します。 
- math.radians(x)¶
- 角 x を度からラジアンに変換します。 
三角関数¶
- math.acos(x)¶
- x の逆余弦を、ラジアンで返します。結果は - 0と- piの間です。
- math.asin(x)¶
- x の逆正弦を、ラジアンで返します。結果は - -pi/2と- pi/2の間です。
- math.atan(x)¶
- x の逆正接を、ラジアンで返します。結果は - -pi/2と- pi/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.sin(x)¶
- x ラジアンの正弦を返します。 
- math.tan(x)¶
- x ラジアンの正接を返します。 
双曲線関数¶
Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles.
- 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 - Added in version 3.2. 
- math.erfc(x)¶
- x の相補誤差関数を返します。相補誤差関数 は - 1.0 - erf(x)と定義されます。この関数は、1からの引き算が 桁落ち をするような大きな x に対し使われます。- Added in version 3.2. 
- math.lgamma(x)¶
- x のガンマ関数の絶対値の自然対数を返します。 - Added in version 3.2. 
定数¶
- math.pi¶
- 利用可能なだけの精度の数学定数 π = 3.141592... (円周率)。 
- math.e¶
- 利用可能なだけの精度の数学定数 e = 2.718281... (自然対数の底)。 
- math.tau¶
- The mathematical constant τ = 6.283185..., to available precision. Tau is a circle constant equal to 2π, the ratio of a circle's circumference to its radius. To learn more about Tau, check out Vi Hart's video Pi is (still) Wrong, and start celebrating Tau day by eating twice as much pie! - Added in version 3.6. 
- math.inf¶
- 浮動小数の正の無限大です。(負の無限大には - -math.infを使います。)- float('inf')の出力と等価です。- Added in version 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.nanand- float('nan')are not considered to equal to any other numeric value, including themselves. To check whether a number is a NaN, use the- isnan()function to test for NaNs instead of- isor- ==. Example:- >>> import math >>> math.nan == math.nan False >>> float('nan') == float('nan') False >>> math.isnan(math.nan) True >>> math.isnan(float('nan')) True - Added in version 3.5. - バージョン 3.11 で変更: 常に利用出来るようになりました。 
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モジュール
- これらの多くの関数の複素数版。