math
模块提供了很多与数学相关的函数,本教程只列举了其中一部分。
方法名 | 功能和作用 |
---|---|
math.ceil(x) |
取大于等于x的最小的整数值,如果x是一个整数,则返回x |
math.fabs(x) |
返回x的绝对值 |
math.floor(x) |
floor() 取小于等于x的最大的整数值,如果x是一个整数,则返回自身 |
log(x,a) |
如果不指定a,则默认以e为基数,a参数给定时,将 x 以a为底的对数返回 |
math.log10(x) |
返回x的以10为底的对数 |
math.log2(x) |
返回x的基2对数 |
math.pi |
数字常量,圆周率 |
math.pow(x, y) |
返回x的y次方,即 x**y |
math.sqrt(x) |
求x的平方根 |
math
模块是Python标准库中提供数学运算函数的模块,
包含各种常见的数学运算功能。使用前需要先导入:
import math
向上取整 → 5
math.ceil(4.3)
5
向下取整 → 4
math.floor(4.7)
4
绝对值 → 5.0 (返回浮点数)
math.fabs(-5)
5.0
取模 → 1.0 (浮点数取模)
math.fmod(10, 3)
1.0
- 阶乘与组合
5的阶乘 → 120
math.factorial(5)
120
组合数C(5,2) → 10
math.comb(5, 2)
10
排列数P(5,2) → 20
math.perm(5, 2)
20
- 符号处理
将第二个参数的符号赋给第一个数 → -3.5
math.copysign(3.5, -1)
-3.5
2的3次方 → 8.0
math.pow(2, 3)
8.0
平方根 → 3.0
math.sqrt(9)
3.0
e的1次方 → 2.718...
math.exp(1)
2.718281828459045
自然对数 → 1.0
math.log(math.e)
1.0
以10为底的对数 → 2.0
math.log10(100)
2.0
以2为底的对数 → 3.0
math.log2(8)
3.0
sin(π/2) → 1.0
math.sin(math.pi/2)
1.0
cos(π) → -1.0
math.cos(math.pi)
-1.0
tan(π/4) → 1.0
math.tan(math.pi/4)
0.9999999999999999
反三角函数
arcsin(1) → π/2
math.asin(1)
1.5707963267948966
arccos(0) → π/2
math.acos(0)
1.5707963267948966
arctan(1) → π/4
math.atan(1)
0.7853981633974483
角度弧度转换
弧度转角度 → 180.0
math.degrees(math.pi)
180.0
角度转弧度 → π
math.radians(180)
3.141592653589793
双曲正弦
math.sinh(1)
1.1752011936438014
双曲余弦
math.cosh(1)
1.5430806348152437
双曲正切
math.tanh(1)
0.7615941559557649
Γ函数,Γ(n)=(n-1)! → 24.0
math.gamma(5)
24.0
ln(Γ(5)) → ln(24)
math.lgamma(5)
3.178053830347945
误差函数
math.erf(1)
0.8427007929497149
互补误差函数
math.erfc(1)
0.15729920705028513