math是Python内置的一个标准库,它包含了许多执行复杂数学运算的函数。这个也是考纲当中要考的。所以在这里总结分享一下。可以从这里找到:https://docs.python.org/zh-cn/3/library/math.htmlimport mathprint(dir(math))
通过这两条命令就把math所有的函数名称打印出来了。考试的时候也不是全考,也只是其中的一部分。- 功能:计算n的阶乘
- 注意:n必须是非负整数,否则抛出ValueError
print(math.factorial(5)) # 输出: 120 (5! = 5×4×3×2×1)
- 功能:计算多个整数的最大公约数
- 特点:可接受任意数量的整数参数
- 注意:Python 3.5+ 支持多个参数
print(math.gcd(8, 12)) # 输出: 4print(math.gcd(8, 12, 16)) # 输出: 4
- 功能:计算非负整数n的整数平方根(向下取整)
- 特点:Python 3.8+ 引入,比
int(math.sqrt(n))更精确 - 注意:n必须是非负整数
print(math.isqrt(10)) # 输出: 3 (10的整数平方根,向下取整)
- 功能:计算多个整数的最小公倍数
- 特点:Python 3.9+ 引入
- 注意:与gcd互为补充,lcm(a,b) = |a*b|/gcd(a,b)
print(math.lcm(4, 6)) # 输出: 12print(math.lcm(2, 3, 4)) # 输出: 12
- 特点:
- 返回值是浮点数(如
4.0而非4) - 与
int()或trunc()不同,负数向上取整会向0靠近
import mathprint(math.ceil(3.2)) # 输出: 4.0print(math.ceil(-3.2)) # 输出: -3.0
- 功能:x的绝对值(浮点版)
- 特点:
- 总是返回浮点数
- 与内置函数
abs()的区别:abs()可处理整数/复数,fabs只处理浮点数
print(math.fabs(-3.5)) # 输出: 3.5print(math.fabs(3.5)) # 输出: 3.5#print(abs(-3)) # 3 (整数)print(math.fabs(-3)) # 3.0 (浮点数)
- 功能:向下取整,即小于等于x的最大整数
- 特点:
- 返回值是浮点数
- 与
ceil相反,负数向下取整会远离0
- 对比:
floor(3.8) = 3.0floor(-3.8) = -4.0
print(math.floor(3.8)) # 输出: 3.0print(math.floor(-3.8)) # 输出: -4.0
- 功能:除法运算
x / y的余数 - 特点:
- 结果的符号与x相同
- 与
%运算符的区别:x % y的结果符号与y相同
print(math.fmod(10.5, 3.2)) # 输出: 0.9print(math.fmod(-10.5, 3.2)) # 输出: -0.9#对比print(-10.5 % 3.2) # 1.9 (符号与y相同)print(math.fmod(-10.5, 3.2)) # -0.9 (符号与x相同)
math.modf(x)
- 功能:x的小数和整数部分
- 特点:
- 返回元组(小数部分, 整数部分)
- 两部分都保留原始x的符号
- 注意:整数部分也是浮点数(如
3.0)
print(math.modf(3.5)) # 输出: (0.5, 3.0)print(math.modf(-3.5)) # 输出: (-0.5, -3.0)
- 对比:
trunc(3.5) = 3trunc(-3.5) = -3
print(math.trunc(3.5)) # 输出: 3print(math.trunc(-3.5)) # 输出: -3
- 功能:计算x的立方根
- 特点:
- Python 3.11+ 引入
- 与
x ** (1/3)相比,更精确(尤其对负数)
- 注意:返回浮点数,即使结果是整数
import mathprint(math.cbrt(27)) # 输出: 3.0print(math.cbrt(-8)) # 输出: -2.0
- 功能:计算x的y次幂
- 特点:
- 返回浮点数
- 与
**运算符的区别:math.pow总是返回浮点数
print(math.pow(2, 3)) # 输出: 8.0print(math.pow(9, 0.5)) # 输出: 3.0#对比print(2 ** 3) # 8 (整数)print(math.pow(2, 3)) # 8.0 (浮点数)
- 功能:计算x的平方根
- 特点:
- 专为平方根优化,比
x ** 0.5更快更精确 - x必须≥0,否则抛出
ValueError
- 注意:返回浮点数
print(math.sqrt(16)) # 输出: 4.0print(math.sqrt(2)) # 输出: 1.414...
- 功能:计算e的x次幂
- 特点:
- 科学应用:自然增长模型、概率分布
print(math.exp(1)) # 输出: 2.718... (e)print(math.exp(2)) # 输出: 7.389... (e²)
math.exp2(x)
- 功能:计算2的x次幂
- 特点:
- Python 3.11+ 引入
- 比
2 ** x更精确
- 应用:二进制计算、信息论
print(math.exp2(3)) # 输出: 8.0 (2³)print(math.exp2(0.5)) # 输出: 1.414... (√2)
好了,针对考试的话,分享到这里就差不多了。如果是开发的话,在最开始的地方那个网址里面还有更多的介绍。一起沟通,学习。