本篇讲解Python标准库中的math模块。
官方文档:https://docs.python.org/zh-cn/3.8/library/math.html
注:该模块定义的函数不适用于复数;如果需要计算复数,请使用cmath模块中的同名函数。cmath模块官方文档:https://docs.python.org/zh-cn/3.8/library/cmath.html#constants
1.数论与表示函数
函数 | 说明 |
---|---|
math.ceil (x) |
返回 x 的上限,即大于或者等于 x 的最小整数。 |
math.comb (n,k) |
返回不重复且无顺序地从 n 项中选择 k 项的方式总数 |
math.fabs (x) |
返回 x 的绝对值。 |
math.factorial (x) |
以一个整数返回 x 的阶乘。 如果 x 不是整数或为负数时则将引发 ValueError。 |
math.floor (x) |
返回 x 的向下取整,小于或等于 x 的最大整数。 |
math.fmod (x,y) |
求余 |
math.fsum (iterable) |
返回迭代中的精确浮点值。通过跟踪多个中间部分和来避免精度损失。 |
math.gcd (a,b) |
返回整数 a 和 b 的最大公约数。 |
math.isclose (a, b,rel_tol=1e-09) |
若 a 和 b 的值比较接近则返回 True ,否则返回 False (注:IEEE 754特殊值 NaN , inf 和 -inf 将根据IEEE规则处理。具体来说, NaN 不被认为接近任何其他值,包括 NaN , inf 和 -inf 只被认为接近自己。) |
math.isinf (x) |
如果 x 是正或负无穷大,则返回 True ,否则返回 False 。 |
math.isfinite (x) |
如果 x 既不是无穷大也不是NaN,则返回 True ,否则返回 False 。 |
math.isnan (x) |
如果 x 是 NaN(不是数字),则返回 True ,否则返回 False 。 |
math.isqrt (x) |
返回非负整数 n 的整数平方根(这就是对 n 的实际平方根向下取整,或者相当于使得 a² ≤ n 的最大整数 a)。 |
math.modf (x) |
返回 x 的小数和整数部分。两个结果都带有 x 的符号并且是浮点数。 |
math.perm (n,k=None) |
返回不重复且有顺序地从 n 项中选择 k 项的方式总数。 |
math.prod (iterable, *, start=1) |
计算输入的 iterable 中所有元素的积。 积的默认 start 值为 1。 |
math.trunc (x) |
返回 Real 值 x 截断为 Integral(通常是整数)。 |
import math
print(math.ceil(5.0)) # 5
print(math.ceil(5.4)) # 6
print(math.floor(4.0)) # 4
print(math.floor(4.9)) # 4
print(math.trunc(3.14)) # 3
print(math.modf(3.14)) # (0.14000000000000012, 3.0)
print(math.comb(10,4)) # 210
print(math.perm(10,4)) # 5040
print(math.fabs(-2.5)) # 2.5
print(math.factorial(5