内容表

  • math — 数学函数
    • 数论和表示函数
    • 幂和对数函数
    • 三角函数
    • 角度转换
    • 双曲函数
    • 特殊函数
    • 常量

上一话题

numbers — 数值抽象基类

下一话题
就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 数值和数学模块
  9. math — 数学函数

math — 数学函数 ¶


此模块提供对 C 标准定义数学函数的访问。

这些函数无法用于复数;使用的同名函数来自 cmath 模块若要求支持复数。支持复数和那些不支持复数的函数之间的区别,是由于大多数用户不想学习理解复数要求的那么多数学知识。接收异常而不是复杂结果允许更早地检测用作参数的意外复数,所以,程序员可以确定它最初是如何生成的及为什么生成。

此模块提供下列函数。除另有明确说明外,所有返回值是浮点数。

数论和表示函数 ¶

math. ceil ( x ) ¶

返回上限为 x ,最小整数 >= x 。若 x 不是浮点,委托 x.__ceil__ ,其应返回 Integral 值。

math. comb ( n , k ) ¶

Return the number of ways to choose k items from n items without repetition and without order.

评估为 n! / (k! * (n - k)!) 当 k <= n 和评估为 0 当 k > n .

Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of (1 + x)ⁿ .

引发 TypeError 若任一自变量不是整数。引发 ValueError 若任一自变量为负。

Added in version 3.8.

math. copysign ( x , y ) ¶

Return a float with the magnitude (absolute value) of x but the sign of y . On platforms that support signed zeros, copysign(1.0, -0.0) 返回 -1.0 .

math. fabs ( x ) ¶

返回绝对值的 x .

math. factorial ( n ) ¶

返回 n 阶乘按整数。引发 ValueError if n 不是整型或为负。

从 3.9 版起弃用: 接受具有整数值的浮点数 (像 5.0 ) 被弃用。

math. floor ( x ) ¶

Return the floor of x , the largest integer less than or equal to x 。若 x 不是浮点,委托 x.__floor__ ,其应返回 Integral 值。

math. fmod ( x , y ) ¶

返回 fmod(x, y) , as defined by the platform C library. Note that the Python expression x % y may 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*y for some integer n such that the result has the same sign as x and magnitude less than abs(y) 。Python 的 x % y returns 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 % 1e100 is 1e100-1e-100 , which cannot be represented exactly as a float, and rounds to the surprising 1e100 。出于此原因,函数 fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.

math. frexp ( x ) ¶

Return the mantissa and exponent of x as the pair (m, e) . m is a float and e is an integer such that x == m * 2**e exactly. If x 为 0,返回 (0.0, 0) ,否则 0.5 <= abs(m) < 1 . This is used to “pick apart” the internal representation of a float in a portable way.

math. fsum ( iterable ) ¶

Return an accurate floating point sum of values in the iterable. Avoids loss of precision by tracking multiple intermediate partial sums.

The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the typical case where the rounding mode is half-even. On some non-Windows builds, the underlying C library uses extended precision addition and may occasionally double-round an intermediate sum causing it to be off in its least significant bit.

For further discussion and two alternative approaches, see the 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 returns 0 .

Added in version 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 ) ¶

返回 True 若值 a and b 相互接近和 False 否则。

认为 2 个值是否接近,是根据给定的绝对偏差和相对偏差确定的。

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 greater than zero.

abs_tol is the minimum absolute tolerance – useful for comparisons near zero. abs_tol 必须至少为 0。

如果不发生错误,结果将是: abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) .

The IEEE 754 special values of NaN , inf ,和 -inf will be handled according to IEEE rules. Specifically, NaN is not considered close to any other value, including NaN . inf and -inf are only considered close to themselves.

Added in version 3.5.

另请参阅

PEP 485 – 用于测试近似相等的函数

math. isfinite ( x ) ¶

返回 True if x 既不是无穷大也不是 NaN (非数字),和 False 否则。(注意 0.0 is 认为有限)。

Added in version 3.2.

math. isinf ( x ) ¶

返回 True if x 为正无穷大 (或负无穷大),和 False 否则。

math. isnan ( x ) ¶

返回 True if x 为 NaN (非数字),和 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 这样 a ² ≤ n .

For some applications, it may be more convenient to have the least integer a 这样 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) .

Added in version 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 returns 1 .

Added in version 3.9.

math. ldexp ( x , i ) ¶

返回 x * (2**i) . This is essentially the inverse of function frexp() .

math. modf ( x ) ¶

Return the fractional and integer parts of x . Both results carry the sign of x and are floats.

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

Return the floating-point value steps steps after x towards y .

若 x 等于 y ,返回 y ,除非 steps 为 0。

范例:

  • 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() .

Added in version 3.9.

Changed in version 3.12: 添加 steps 自变量。

math. perm ( n , k = None ) ¶

Return the number of ways to choose k items from n items without repetition and with order.

评估为 n! / (n - k)! 当 k <= n 和评估为 0 当 k > n .

若 k 未指定或是 None ,那么 k 默认为 n 且函数返回 n! .

引发 TypeError 若任一自变量不是整数。引发 ValueError 若任一自变量为负。

Added in version 3.8.

math. prod ( iterable , * , start = 1 ) ¶

Calculate the product of all the elements in the input iterable 。默认 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.

Added in version 3.8.

math. remainder ( x , y ) ¶

Return the IEEE 754-style remainder of x with respect to y . For finite x and finite nonzero y , this is the difference x - n*y ,其中 n is the closest integer to the exact value of the quotient x / y 。若 x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n . The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y) .

Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x ,和 remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x . If the result of the remainder operation is zero, that zero will have the same sign as 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. sumprod ( p , q ) ¶

Return the sum of products of values from two iterables p and q .

引发 ValueError if the inputs do not have the same length.

大致相当于:

sum(itertools.starmap(operator.mul, zip(p, q, strict=True)))
													

For float and mixed int/float inputs, the intermediate products and sums are computed with extended precision.

3.12 版添加。

math. trunc ( x ) ¶

返回 x with the fractional part removed, leaving the integer part. This rounds toward 0: trunc() 相当于 floor() for positive x , and equivalent to ceil() for negative x 。若 x 不是浮点,委托 x.__trunc__ ,其应返回 Integral 值。

math. ulp ( x ) ¶

Return the value of the least significant bit of the float x :

  • 若 x 为 NaN (非数字),返回 x .

  • 若 x 为负,返回 ulp(-x) .

  • 若 x is a positive infinity, return x .

  • 若 x is equal to zero, return the smallest positive denormalized representable float (smaller than the minimum positive normalized float, sys.float_info.min ).

  • 若 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”.

另请参阅 math.nextafter() and sys.float_info.epsilon .

Added in version 3.9.

注意, frexp() and modf() have a different call/return pattern than their C equivalents: they take a single argument and return a pair of values, rather than returning their second return value through an ‘output parameter’ (there is no such thing in Python).

对于 ceil() , floor() ,和 modf() functions, note that all floating-point numbers of sufficiently large magnitude are exact integers. Python floats typically carry no more than 53 bits of precision (the same as the platform C double type), in which case any float x with abs(x) >= 2**52 necessarily has no fractional bits.

幂和对数函数 ¶

math. cbrt ( x ) ¶

返回立方根为 x .

Added in version 3.11.

math. exp ( x ) ¶

返回 e 自乘幂 x ,其中 e = 2.718281… 是自然对数的基。这通常更精确比 math.e ** x or pow(math.e, x) .

math. exp2 ( x ) ¶

返回 2 自乘幂 x .

Added in version 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
													

Added in version 3.2.

math. log ( x [ , base ] ) ¶

按 1 自变量,返回自然对数为 x (到基 e ).

按 2 自变量,返回对数为 x 到给定 base ,计算如 log(x)/log(base) .

math. log1p ( x ) ¶

返回自然对数为 1+x (基 e ). The result is calculated in a way which is accurate for x near zero.

math. log2 ( x ) ¶

返回 2 基对数为 x 。这通常更精确比 log(x, 2) .

Added in version 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 ) ¶

返回 10 基对数为 x 。这通常更精确比 log(x, 10) .

math. pow ( x , y ) ¶

返回 x 自乘幂 y . Exceptional cases follow the IEEE 754 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) 始终返回 1.0 ,甚至当 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() 将其 2 自变量转换为类型 float 。使用 ** 或内置 pow() 函数用于计算准确整数幂。

3.11 版改变: 特殊情况 pow(0.0, -inf) and pow(-0.0, -inf) 被改为返回 inf 而不是引发 ValueError , for consistency with IEEE 754.

math. sqrt ( x ) ¶

返回平方根为 x .

三角函数 ¶

math. acos ( x ) ¶

返回 acos (反余弦) 为 x (以弧度为单位)。结果介于 0 and pi .

math. asin ( x ) ¶

返回 asin (反正弦) 为 x (以弧度为单位)。结果介于 -pi/2 and pi/2 .

math. atan ( x ) ¶

返回 atan (反正切) 为 x (以弧度为单位)。结果介于 -pi/2 and pi/2 .

math. atan2 ( y , x ) ¶

返回 atan(y / x) (以弧度为单位)。结果介于 -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 ,但 atan2(-1, -1) is -3*pi/4 .

math. cos ( x ) ¶

返回 cos (余弦) 为 x 弧度。

math. dist ( p , q ) ¶

返回 Euclidean (欧几里德) 距离介于 2 点 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)))
													

Added in version 3.8.

math. hypot ( * coordinates ) ¶

返回 Euclidean (欧几里德) 范数 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.

对于 2 维点 (x, y) , this is equivalent to computing the hypotenuse of a right triangle using the Pythagorean theorem, sqrt(x*x + y*y) .

3.8 版改变: 增加支持 n 维点。以前,只支持 2 维情况。

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 ) ¶

返回 sin (正弦) 为 x 弧度。

math. tan ( x ) ¶

返回 tan (正切) 为 x 弧度。

角度转换 ¶

math. degrees ( x ) ¶

转换角度 x 从弧度到度。

math. radians ( x ) ¶

转换角度 x 从度到弧度。

双曲函数 ¶

双曲函数 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 ) ¶

返回 误差函数 at x .

The erf() function can be used to compute traditional statistical functions such as the 累积标准正态分布 :

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 ) ¶

Return the complementary error function at x 。 互补误差函数 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 .

Added in version 3.2.

math. gamma ( x ) ¶

返回 伽玛函数 at x .

Added in version 3.2.

math. lgamma ( x ) ¶

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

Added in version 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!

Added in version 3.6.

math. inf ¶

A floating-point positive infinity. (For negative infinity, use -math.inf .) Equivalent to the output of 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.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 == 。范例:

>>> 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 版改变: 它现在始终可用。

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

很多这些函数的复数版本。

内容表

  • math — 数学函数
    • 数论和表示函数
    • 幂和对数函数
    • 三角函数
    • 角度转换
    • 双曲函数
    • 特殊函数
    • 常量

上一话题

numbers — 数值抽象基类

下一话题

cmath — 用于复数的数学函数

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 数值和数学模块
  9. math — 数学函数
  10. 版权所有  © 2014-2026 乐数软件    

    工业和信息化部: 粤ICP备14079481号-1