math模块是 Python 内置的一个模块,用于执行各种数学运算。这个模块提供了多种内置的方法来完成不同的数学任务。
注意:math 模块的方法不适用于复数。对于复数的运算,可以使用 cmath 模块。
导入 math 模块
在使用 math 模块的方法之前,你需要将 math 模块导入到你的代码中。以下是语法:
import math
Python math 模块的方法
以下是根据其功能和用途分类的 math 模块方法列表。
理论与表示方法
Python 包含了以下理论与表示函数在 math 模块中:
| 序号 |
函数 & 描述 |
| 1 |
math.ceil(x) |
| 2 |
math.comb(n, k) |
| 3 |
math.copysign(x, y) |
| 4 |
math.cmp(x, y) |
| 5 |
math.fabs(x) |
| 6 |
math.factorial(n) |
| 7 |
math.floor(x) |
| 8 |
math.fmod(x, y) |
| 9 |
math.frexp(x) |
| 10 |
math.fsum(iterable) |
| 11 |
math.gcd(*integers) |
| 12 |
math.isclose() |
| 13 |
math.isfinite(x) |
| 14 |
math.isinf(x) |
| 15 |
math.isnan(x) |
| 16 |
math.isqrt(n) |
| 17 |
math.lcm(*integers) |
| 18 |
math.ldexp(x, i) |
| 19 |
math.modf(x) |
| 20 |
math.nextafter(x, y, steps) |
| 21 |
math.perm(n, k) |
| 22 |
math.prod(iterable, *, start) |
| 23 |
math.remainder(x,y) |
| 24 |
math.trunc(x) |
| 25 |
math.ulp(x) |
幂和对数方法
| 序号 |
函数 & 描述 |
| 1 |
math.cbrt(x) |
| 2 |
math.exp(x) |
| 3 |
math.exp2(x) |
| 4 |
math.expm1(x) |
| 5 |
math.log(x) |
| 6 |
math.log1p(x) |
| 7 |
math.log2(x) |
| 8 |
math.log10(x) |
| 9 |
math.pow(x, y) |
| 10 |
math.sqrt(x) |
三角方法
| 序号 |
函数 & 描述 |
| 1 |
math.acos(x) |
| 2 |
math.asin(x) |
| 3 |
math.atan(x) |
| 4 |
math.atan2(y, x) |
| 5 |
math.cos(x) |
| 6 |
math.sin(x) |
| 7 |
math.tan(x) |
| 8 |
math.hypot(x, y) |
角度转换方法
| 序号 |
函数 & 描述 |
| 1 |
math.degrees(x) |
| 2 |
math.radians(x) |
数学常量
Python math 模块定义了以下数学常量:
| 序号 |
常量 & 描述 |
| 1 |
math.pi |
| 2 |
math.e |
| 3 |
math.tau |
| 4 |
math.inf |
| 5 |
math.nan |
双曲方法
| 序号 |
函数 & 描述 |
| 1 |
math.acosh(x) |
| 2 |
math.asinh(x) |
| 3 |
math.atanh(x) |
| 4 |
math.cosh(x) |
| 5 |
math.sinh(x) |
| 6 |
math.tanh(x) |
特殊方法
| 序号 |
函数 & 描述 |
| 1 |
math.erf(x) |
| 2 |
math.erfc(x) |
| 3 |
math.gamma(x) |
| 4 |
math.lgamma(x) |
示例使用
下面的例子演示了如何使用 math 模块及其方法:
import math
print(math.sqrt(9))
print(math.pow(3, 3))
print(math.exp(1))
print(math.log(100, 10))
print(math.factorial(4))
print(math.gcd(12, 3))
输出:
3.0
27.0
2.718281828459045
2.0
24
3