math --- 數學函式


此模組提供對常見數學函式與常數的存取,包括於 C 標準中定義的那些。

這些函式不支援複數;若你需要計算複數,請使用 cmath 模組的同名函式。這是因為大多數的使用者並不想學習那麼多理解複數所需的數學概念,所以根據支援複數與否分為兩種函式。收到一個例外而非複數回傳值,有助於程式設計師提早察覺參數中包含非預期的複數,進而從源頭查出導致此情況的原因。

此模組提供下列函式。除非特意註明,否則回傳值皆為浮點數。

數論函式

comb(n, k)

n 個物品中不重複且不考慮排序地取出 k 個物品的方法數。

factorial(n)

n factorial

gcd(*integers)

Greatest common divisor of the integer arguments

isqrt(n)

Integer square root of a nonnegative integer n

lcm(*integers)

Least common multiple of the integer arguments

perm(n, k)

n 個物品中不重複但考慮排序地取出 k 個物品的方法數。

Floating point arithmetic

ceil(x)

Ceiling of x, the smallest integer greater than or equal to x

fabs(x)

x 的絕對值。

floor(x)

Floor of x, the largest integer less than or equal to x

fma(x, y, z)

Fused multiply-add operation: (x * y) + z

fmod(x, y)

Remainder of division x / y

modf(x)

Fractional and integer parts of x

remainder(x, y)

Remainder of x with respect to y

trunc(x)

Integer part of x

浮點數操作函式

copysign(x, y)

Magnitude (absolute value) of x with the sign of y

frexp(x)

Mantissa and exponent of x

isclose(a, b, rel_tol, abs_tol)

Check if the values a and b are close to each other

isfinite(x)

Check if x is neither an infinity nor a NaN

isinf(x)

Check if x is a positive or negative infinity

isnan(x)

Check if x is a NaN (not a number)

ldexp(x, i)

x * (2**i), inverse of function frexp()

nextafter(x, y, steps)

Floating-point value steps steps after x towards y

ulp(x)

Value of the least significant bit of x

Power, exponential and logarithmic functions

cbrt(x)

Cube root of x

exp(x)

e raised to the power x

exp2(x)

2 raised to the power x

expm1(x)

e raised to the power x, minus 1

log(x, base)

Logarithm of x to the given base (e by default)

log1p(x)

Natural logarithm of 1+x (base e)

log2(x)

Base-2 logarithm of x

log10(x)

Base-10 logarithm of x

pow(x, y)

x raised to the power y

sqrt(x)

x 的平方根

Summation and product functions

dist(p, q)

Euclidean distance between two points p and q given as an iterable of coordinates

fsum(iterable)

Sum of values in the input iterable

hypot(*coordinates)

Euclidean norm of an iterable of coordinates

prod(iterable, start)

Product of elements in the input iterable with a start value

sumprod(p, q)

Sum of products from two iterables p and q

Angular conversion

degrees(x)

Convert angle x from radians to degrees

radians(x)

Convert angle x from degrees to radians

Trigonometric functions

acos(x)

Arc cosine of x

asin(x)

Arc sine of x

atan(x)

Arc tangent of x

atan2(y, x)

atan(y / x)

cos(x)

Cosine of x

sin(x)

Sine of x

tan(x)

Tangent of x

Hyperbolic functions

acosh(x)

Inverse hyperbolic cosine of x

asinh(x)

Inverse hyperbolic sine of x

atanh(x)

Inverse hyperbolic tangent of x

cosh(x)

Hyperbolic cosine of x

sinh(x)

Hyperbolic sine of x

tanh(x)

Hyperbolic tangent of x

Special functions

erf(x)

Error function at x

erfc(x)

Complementary error function at x

gamma(x)

Gamma function at x

lgamma(x)

Natural logarithm of the absolute value of the Gamma function at x

常數

pi

π = 3.141592...

e

e = 2.718281...

tau

τ = 2π = 6.283185...

inf

正無限大

nan

"Not a number" (NaN)

數論函式

math.comb(n, k)

回傳從 n 個物品中不重複且不考慮排序地取出 k 個物品的方法數。

k <= n 時其值為 n! / (k! * (n - k)!),否則其值為 0

因為此值等同於 (1 + x)ⁿ 進行多項式展開後第 k 項的係數,所以又稱為二項式係數。

當任一參數非整數型別時會引發 TypeError。當任一參數為負數時會引發 ValueError

在 3.8 版被加入.

math.factorial(n)

Return factorial of the nonnegative integer n.

在 3.10 版的變更: 現在已經不允許傳入其值為整數的浮點數(如:5.0)。

math.gcd(*integers)

回傳指定整數引數的最大公因數。若存在任一非零引數,回傳值為所有引數共有因數中最大的正整數。若所有引數皆為零,則回傳值為 0gcd() 若未傳入任何引數也將回傳 0

在 3.5 版被加入.

在 3.9 版的變更: 新增支援任意數量的引數。先前僅支援兩個引數。

math.isqrt(n)

回傳非負整數 n 的整數平方根。此值為 n 精確平方根經下取整的值,亦等同於滿足 a² ≤ n 的最大整數值 a

於有些應用程式中,取得滿足 n ≤ a² 的最小整數值 a ── 或者說 n 精確平方根經上取整的值 ── 會更加方便。對正數 n,此值可使用 a = 1 + isqrt(n - 1) 計算。

在 3.8 版被加入.

math.lcm(*integers)

回傳指定整數引數的最小公倍數。若所有引數值皆非零,回傳值為所有引數共有倍數中最小的正整數。若存在任一引數值為零,則回傳值為 0lcm() 若未傳入任何引數將回傳 1

在 3.9 版被加入.

math.perm(n, k=None)

回傳從 n 個物品中不重複且考慮排序地取出 k 個物品的方法數。

k <= n 時其值為 n! / (n - k)!,否則其值為 0

若未給定 k 或其值為 None,則 k 值預設為 n,且函式回傳 n!

當任一參數非整數型別時會引發 TypeError。當任一參數為負數時會引發 ValueError

在 3.8 版被加入.

計算傳入的 iterable 中所有元素的乘積。預設的乘積起始值 start1

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)

融合乘加運算。回傳 (x * y) + z,用近似於無限精度及範圍的方式計算,而後一次轉換為 float 格式。此操作通常能提供比運算式 (x * y) + z 更高的準確度。

此函式遵循 IEEE-754 標準中規範的融合乘加(fusedMultiplyAdd)運算。該標準保留一種由實作決定的案例,即 fma(0, inf, nan)fma(inf, 0, nan) 的結果;在這些案例中,math.fma 回傳 NaN 且不會引發例外。

在 3.13 版被加入.

math.fmod(x, y)

回傳 x / y 的浮點數餘數,其以平臺上的 C 函式庫 fmod(x, y) 函式定義。請注意此函式與 Python 運算式 x % y 可能不會回傳相同結果。C 標準要求 fmod(x, y) 的回傳值完全等同(數學定義上,即無限精度)於 x - n*yn 為可使回傳值與 x 同號且長度小於 abs(y) 的整數。Python 運算式 x % y 的回傳值則與 y 同號,且可能無法精確地計算浮點數引數。例如:fmod(-1e-100, 1e100) 的值為 -1e-100,但 Python 運算式 -1e-100 % 1e100 的結果為 1e100-1e-100,此值無法準確地表示成浮點數,並會四捨五入為出乎意料的 1e100。因此,處理浮點數時通常會選擇函式 fmod(),而處理整數時會選擇 Python 運算式 x % y

math.modf(x)

回傳 x 的小數及整數部分,兩者皆為與 x 同號的浮點數。

請注意 modf() 的呼叫/回傳模式與 C 語言中相應的函式不同:它們接受一個引數並回傳一對值,而非透過一個「輸出參數(output parameter)」傳遞第二個回傳值(Python 沒有那種東西)。

math.remainder(x, y)

回傳 xy 根據 IEEE 754 定義的餘數。對有限數 x 及有限非零數 y,該值為 x - n*y 差值,n 是最接近商數 x / y 的整數。若 x / y 剛好位於兩個連續整數的正中間,n 為最接近的數。因此該餘數 r = remainder(x, y) 總是滿足 abs(r) <= 0.5 * abs(y)

特殊情況遵循 IEEE 754:特別是,對任何有限數 xremainder(x, math.inf) 的值為 x;對任何非 NaN 值的 xremainder(x, 0)remainder(math.inf, x) 會引發 ValueError。若取餘數操作的結果為零,則該零值會與 x 同號。

在使用 IEEE 754 浮點標準中二進制浮點數的平台上,此操作的結果必能精準表示,不會出現捨入誤差。

在 3.7 版被加入.

math.trunc(x)

回傳去除小數部分而僅餘整數部分的 x。此函式會向零捨入:若 x 為正值,trunc() 等價於 floor();若 x 為負值,trunc() 等價於 ceil()。若 x 非浮點數,此函式將委派給 x.__trunc__,而後回傳一 Integral 值。

使用 ceil()floor()modf() 三個函式時,請注意 所有 足夠大的浮點數都是精確的整數。Python 的浮點數型別的精確度通常不會超過 53 位元(與 C 語言 double 型別相同),因此當浮點數 x 滿足 abs(x) >= 2**52 時,它必然沒有小數部分。

Floating point manipulation functions

math.copysign(x, y)

回傳與 x 相同長度(絕對值)且與 y 同號的浮點數。在支援帶符號零的平臺上,copysign(1.0, -0.0) 回傳 -1.0

math.frexp(x)

(m, e) 對的格式回傳 x 的尾數 m 及指數 em 是浮點數而 e 是整數,且兩者精確地使 x == m * 2**e。若 x 為零,回傳 (0.0, 0),否則令 0.5 <= abs(m) < 1。此函式用於以可攜的方式「分割」浮點數內部表示法。

請注意 frexp() 的呼叫/回傳模式與 C 語言中相應的函式不同:它們接受一個引數並回傳一對值,而非透過一個「輸出參數(output parameter)」傳遞第二個回傳值(Python 沒有那種東西)。

math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)

ab 兩值足夠接近便回傳 True,否則回傳 False

兩數是否足夠接近取決於給定的絕對及相對容許偏差 (tolerance)。如果沒有錯誤發生,結果將為:abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)

rel_tol 為相對容許偏差 ── ab 兩數差的最大容許值,與 ab 兩數的絕對值中較大者相關。例如欲設置 5% 的容許偏差,則傳入 rel_tol=0.05。其預設值為 1e-09,該值可確保兩數於大約 9 個十進數位內相同。rel_tol 須不為負且小於 1.0

abs_tol is the absolute tolerance; it defaults to 0.0 and it must be nonnegative. When comparing x to 0.0, isclose(x, 0) is computed as abs(x) <= rel_tol  * abs(x), which is False for any nonzero x and rel_tol less than 1.0. So add an appropriate positive abs_tol argument to the call.

定義於 IEEE 754 浮點標準中的特殊值 NaNinf-inf 會根據該標準處理。更明確地說,NaN 不會與包含自身在內的任何數字足夠接近,而 inf-inf 皆只與自身接近。

在 3.5 版被加入.

也參考

PEP 485 ── 用於測試近似相等的函式

math.isfinite(x)

x 不是無限值或 NaN 便回傳 True,否則回傳 False。(注意 0.0 被視為有限數。)

在 3.2 版被加入.

math.isinf(x)

x 是正無限值或負無限值便回傳 True,否則回傳 False

math.isnan(x)

x 是 NaN ── 即非數值(NaN, not a number)── 便回傳 True,否則回傳 False

math.ldexp(x, i)

回傳 x * (2**i)。此函式本質上為 frexp() 的反函式。

math.nextafter(x, y, steps=1)

回傳 xy steps 步的浮點數值。

除非 steps 為零,否則當 xy 相等時回傳 y

範例:

  • math.nextafter(x, math.inf) 增加:往正無限。

  • math.nextafter(x, -math.inf) 減少:往負無限。

  • math.nextafter(x, 0.0) 靠近零。

  • math.nextafter(x, math.copysign(math.inf, x)) 遠離零。

另請參閱 math.ulp()

在 3.9 版被加入.

在 3.12 版的變更: 新增 steps 引數。

math.ulp(x)

回傳浮點數 x 的最低有效位元:

  • x 為 NaN(非數值),回傳 x

  • x 為負值,回傳 ulp(-x)

  • x 為正無限值,回傳 x

  • x 等於零,回傳反正規化可表示的最小正浮點數(此值小於正規化可表示的最小正浮點數 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

在 3.9 版被加入.

Power, exponential and logarithmic functions

math.cbrt(x)

Return the cube root of x.

在 3.11 版被加入.

math.exp(x)

Return e raised to the power x, where e = 2.718281... is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x).

math.exp2(x)

Return 2 raised to the power x.

在 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) - 1 can 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

在 3.2 版被加入.

math.log(x[, base])

With one argument, return the natural logarithm of x (to base e).

With two arguments, return the logarithm of x to the given base, calculated as log(x)/log(base).

math.log1p(x)

Return the natural logarithm of 1+x (base e). The result is calculated in a way which is accurate for x near zero.

math.log2(x)

Return the base-2 logarithm of x. This is usually more accurate than log(x, 2).

在 3.3 版被加入.

也參考

int.bit_length() returns the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros.

math.log10(x)

Return the base-10 logarithm of x. This is usually more accurate than 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.

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.

在 3.11 版的變更: The special cases pow(0.0, -inf) and pow(-0.0, -inf) were changed to return inf instead of raising ValueError, for consistency with IEEE 754.

math.sqrt(x)

Return the square root of x.

Summation and product functions

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.fsum(iterable)

回傳可疊代物件(iterable)中所有值的精確浮點數和。透過追蹤過程中多個部分和(partial sum)以避免精確度損失。

此演算法準確性奠基於保證 IEEE-754 浮點標準及典型奇進偶捨(half-even)模式。於有些非 Windows 平台建置時,底層 C 函式庫使用延伸精度加法運算,而可能導致對過程中同一部分和重複捨入,並使其最低有效位不如預期。

更深入的討論及兩種替代做法請參閱 ASPN cookbook recipes 精準的浮點數總和

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.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.sumprod(p, q)

回傳兩個可疊代物件 pq 各值乘積的總和。

若兩個傳入物件長度不同會引發 ValueError

約等價於::

sum(map(operator.mul, p, q, strict=True))

對浮點數或混合整數及浮點數的傳入物件,其過程中的乘積及總和皆使用延伸精度計算。

在 3.12 版被加入.

Angular conversion

math.degrees(x)

Convert angle x from radians to degrees.

math.radians(x)

Convert angle x from degrees to radians.

Trigonometric functions

math.acos(x)

Return the arc cosine of x, in radians. The result is between 0 and pi.

math.asin(x)

Return the arc sine of x, in radians. The result is between -pi/2 and pi/2.

math.atan(x)

Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2.

math.atan2(y, x)

Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. For example, atan(1) and atan2(1, 1) are both pi/4, but atan2(-1, -1) is -3*pi/4.

math.cos(x)

Return the cosine of x radians.

math.sin(x)

Return the sine of x radians.

math.tan(x)

Return the tangent of x radians.

Hyperbolic functions

Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas instead of circles.

math.acosh(x)

Return the inverse hyperbolic cosine of x.

math.asinh(x)

Return the inverse hyperbolic sine of x.

math.atanh(x)

Return the inverse hyperbolic tangent of x.

math.cosh(x)

Return the hyperbolic cosine of x.

math.sinh(x)

Return the hyperbolic sine of x.

math.tanh(x)

Return the hyperbolic tangent of x.

特殊函式

math.erf(x)

Return the error function at 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)

Return the complementary error function at x. The complementary error function is defined as 1.0 - erf(x). It is used for large values of x where a subtraction from one would cause a loss of significance.

在 3.2 版被加入.

math.gamma(x)

Return the Gamma function at x.

在 3.2 版被加入.

math.lgamma(x)

Return the natural logarithm of the absolute value of the Gamma function at x.

在 3.2 版被加入.

常數

math.pi

The mathematical constant π = 3.141592..., to available precision.

math.e

The mathematical constant e = 2.718281..., to available precision.

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!

在 3.6 版被加入.

math.inf

A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of 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 and 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 is 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.5 版被加入.

在 3.11 版的變更: It is now always available.

CPython 實作細節: The math module consists mostly of thin wrappers around the platform C math library functions. Behavior in exceptional cases follows Annex F of the C99 standard where appropriate. The current implementation will raise ValueError for invalid operations like sqrt(-1.0) or log(0.0) (where C99 Annex F recommends signaling invalid operation or divide-by-zero), and OverflowError for results that overflow (for example, exp(1000.0)). A NaN will not be returned from any of the functions above unless one or more of the input arguments was a NaN; in that case, most functions will return a NaN, but (again following C99 Annex F) there are some exceptions to this rule, for example pow(float('nan'), 0.0) or hypot(float('nan'), float('inf')).

Note that Python makes no effort to distinguish signaling NaNs from quiet NaNs, and behavior for signaling NaNs remains unspecified. Typical behavior is to treat all NaNs as though they were quiet.

也參考

cmath 模組

Complex number versions of many of these functions.