Python3 math 模块
在 Python 中,
math
模块是处理基础数学运算的核心库,提供了从简单的加减乘除到复杂的三角函数、对数运算等一系列工具函数。与 Python 内置的算术运算符(如 +
、*
、**
)相比,math
模块的函数在精度控制、特殊值处理(如无穷大、NaN)和数学专业运算(如阶乘、三角函数)上更具优势。本文将系统解析 math
模块的常用函数、常量及实战场景,帮助你高效完成科学计算任务。一、math 模块基础:导入与特性
1. 模块导入
math
是 Python 标准库,无需额外安装,直接导入即可使用:import math
2. 核心特性
- 浮点数为核心:
math
模块的函数几乎都以浮点数(float
)为输入和输出,即使输入是整数,返回值也会转换为浮点数(如math.factorial(5)
返回120.0
吗?不,阶乘返回整数,这是个例外)。 - 精度保障:基于 C 语言的数学库实现,计算精度高于纯 Python 实现的运算。
- 不支持复数:若需处理复数运算,需使用
cmath
模块(如cmath.sqrt(-1)
可计算虚数单位j
)。
二、常用常量:数学计算的基础值
math
模块定义了多个常用数学常量,避免了手动输入的误差,直接调用即可:常量 | 描述 | 近似值 |
---|---|---|
math.pi |
圆周率(π) | 3.1415926535... |
math.e |
自然常数(e) | 2.7182818284... |
math.tau |
圆周率的 2 倍(τ = 2π) | 6.2831853071... |
math.inf |
正无穷大(负无穷大为 -math.inf ) |
— |
math.nan |
非数字(Not a Number,如 0/0 的结果) | — |
示例:利用常量计算圆的面积和周长
import math
radius = 5.0
# 圆的面积 = πr²
area = math.pi * math.pow(radius, 2)
# 圆的周长 = 2πr = τr
circumference = math.tau * radius
print(f"半径为 {radius} 的圆:")
print(f"面积 = {area:.2f}") # 输出:78.54
print(f"周长 = {circumference:.2f}") # 输出:31.42
三、基础数学运算:取整、绝对值与阶乘
1. 取整函数
math
提供了多种取整方式,适用于不同场景:函数 | 功能描述 | 示例 |
---|---|---|
math.ceil(x) |
向上取整(返回大于等于 x 的最小整数) | math.ceil(2.3) → 3 |
math.floor(x) |
向下取整(返回小于等于 x 的最大整数) | math.floor(2.7) → 2 |
math.trunc(x) |
截断小数部分(仅保留整数部分,类似 int(x) ) |
math.trunc(-2.7) → -2 |
math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0) |
判断两个浮点数是否接近(避免直接用 == 比较精度问题) |
math.isclose(0.1+0.2, 0.3) → True |
注意:
ceil
和 floor
返回浮点数(如 3.0
),而 trunc
返回整数(如 3
)。2. 绝对值与符号
-
math.fabs(x)
:返回 x 的绝对值(始终为浮点数,与内置abs()
不同,abs(-3)
返回整数3
)。print(math.fabs(-5)) # 输出:5.0 print(math.fabs(3.2)) # 输出:3.2
-
math.copysign(x, y)
:返回 x 的绝对值,符号与 y 相同(用于统一符号)。print(math.copysign(5, -3)) # 输出:-5.0(x=5的绝对值,符号同y=-3) print(math.copysign(-5, 3.2)) # 输出:5.0(x=-5的绝对值,符号同y=3.2)
3. 阶乘与组合数
-
math.factorial(x)
:返回 x 的阶乘(x 必须是非负整数,否则报错)。print(math.factorial(5)) # 输出:120(5! = 5×4×3×2×1) print(math.factorial(0)) # 输出:1(0! 定义为1)
-
组合数计算(需结合阶乘):从 n 个元素中选 k 个的组合数
C(n,k) = n!/(k!·(n-k)!)
。def comb(n, k): if k < 0 or k > n: return 0 return math.factorial(n) // (math.factorial(k) * math.factorial(n - k)) print(comb(5, 2)) # 输出:10(5选2的组合数)
4. 最大公约数与最小公倍数
-
math.gcd(a, b)
:返回 a 和 b 的最大公约数(仅接受非负整数,0 与 x 的 gcd 是 x 的绝对值)。print(math.gcd(12, 18)) # 输出:6 print(math.gcd(0, 5)) # 输出:5
-
math.lcm(a, b)
:返回 a 和 b 的最小公倍数(Python 3.9+ 新增,非负整数)。print(math.lcm(4, 6)) # 输出:12 print(math.lcm(3, 7)) # 输出:21(互质数的lcm是乘积)
四、幂运算与对数函数:指数、平方根与对数
1. 幂运算
-
math.pow(x, y)
:返回 x 的 y 次幂(x**y
),但与内置pow()
有两点区别:math.pow
始终返回浮点数(如math.pow(2, 3) → 8.0
);- 不支持第三个参数(模运算,如
pow(2, 3, 5)
内置支持,math.pow
不支持)。
print(math.pow(2, 3)) # 输出:8.0 print(math.pow(10, -2)) # 输出:0.01(10的-2次方)
-
math.exp(x)
:返回自然常数 e 的 x 次幂(e^x
)。print(math.exp(1)) # 输出:2.718281828459045(e^1) print(math.exp(0)) # 输出:1.0(e^0 = 1)
-
math.expm1(x)
:返回e^x - 1
(适合 x 接近 0 时,精度高于math.exp(x) - 1
)。print(math.expm1(0.0001)) # 输出:0.00010000500016667083 print(math.exp(0.0001) - 1) # 输出:0.00010000500016667083(此处精度相同,小值时更优)
2. 平方根与开方
-
math.sqrt(x)
:返回 x 的平方根(x 必须是非负数,否则抛ValueError
)。print(math.sqrt(25)) # 输出:5.0 print(math.sqrt(2)) # 输出:1.4142135623730951
-
其他开方运算:如立方根可通过
math.pow(x, 1/3)
实现。print(math.pow(8, 1/3)) # 输出:2.0(8的立方根)
3. 对数函数
math
模块的对数函数默认以自然常数 e 为底,也支持指定底数:函数 | 功能描述 | 示例 |
---|---|---|
math.log(x) |
返回 x 的自然对数(ln x),x > 0 | math.log(math.e) → 1.0 |
math.log(x, base) |
返回以 base 为底的 x 的对数(base > 0 且 ≠1) | math.log(100, 10) → 2.0 |
math.log10(x) |
返回 x 的常用对数(lg x,以 10 为底),x > 0 | math.log10(1000) → 3.0 |
math.log2(x) |
返回 x 的以 2 为底的对数,x > 0(Python 3.3+) | math.log2(8) → 3.0 |
math.log1p(x) |
返回 ln(1 + x) (适合 x 接近 0 时,精度更高) |
math.log1p(0) → 0.0 |
示例:计算 pH 值(pH = -lg [H⁺],[H⁺] 为氢离子浓度)
def calculate_ph(h_ion_concentration):
if h_ion_concentration <= 0:
raise ValueError("氢离子浓度必须为正数")
return -math.log10(h_ion_concentration)
print(calculate_ph(1e-7)) # 输出:7.0(中性溶液)
print(calculate_ph(1e-3)) # 输出:3.0(酸性溶液)
五、三角函数:弧度与角度的转换与运算
math
模块的三角函数参数均为弧度(而非角度),需注意单位转换。1. 角度与弧度转换
math.radians(deg)
:将角度转换为弧度(180° = π 弧度)。math.degrees(rad)
:将弧度转换为角度。
# 将 90° 转换为弧度(π/2)
print(math.radians(90)) # 输出:1.5707963267948966(≈π/2)
# 将 π 弧度转换为角度(180°)
print(math.degrees(math.pi)) # 输出:180.0
2. 基本三角函数
函数 | 功能描述(参数为弧度) | 示例(90° 对应 π/2 弧度) |
---|---|---|
math.sin(x) |
正弦函数 | math.sin(math.pi/2) → 1.0 |
math.cos(x) |
余弦函数 | math.cos(math.pi) → -1.0 |
math.tan(x) |
正切函数 | math.tan(math.pi/4) → 1.0 |
3. 反三角函数
反三角函数返回值为弧度,需转换为角度时用
math.degrees()
:函数 | 功能描述(返回弧度) | 示例(返回值转换为角度) |
---|---|---|
math.asin(x) |
反正弦(x ∈ [-1, 1]) | math.degrees(math.asin(1)) → 90.0 |
math.acos(x) |
反余弦(x ∈ [-1, 1]) | math.degrees(math.acos(-1)) → 180.0 |
math.atan(x) |
反正切 | math.degrees(math.atan(1)) → 45.0 |
math.atan2(y, x) |
已知 y 和 x 求反正切(更精确) | math.degrees(math.atan2(1, 1)) → 45.0 |
示例:计算直角三角形的锐角角度
# 直角三角形的对边=3,邻边=4,求锐角 A(对边对应的角)
opposite = 3.0 # 对边
adjacent = 4.0 # 邻边
# 方法1:用 atan(对边/邻边)
angle_rad = math.atan(opposite / adjacent)
angle_deg = math.degrees(angle_rad)
print(f"角度 A = {angle_deg:.1f}°") # 输出:36.9°
# 方法2:用 atan2(对边, 邻边)(更推荐,处理符号更准确)
angle_rad2 = math.atan2(opposite, adjacent)
angle_deg2 = math.degrees(angle_rad2)
print(f"角度 A = {angle_deg2:.1f}°") # 输出:36.9°
六、特殊函数:伽马函数、双曲函数等
math
模块还包含一些高级数学函数,适用于科学计算场景:1. 伽马函数(Gamma function)
math.gamma(x)
:伽马函数 Γ(x) 是阶乘的推广,满足 Γ(n) = (n-1)!(n 为正整数)。print(math.gamma(5)) # 输出:24.0(等价于 4! = 24)
print(math.gamma(0.5)) # 输出:1.77245385091(√π,约1.772)
2. 双曲函数
双曲函数是指数函数的组合,常用于工程和物理计算:
函数 | 功能描述 | 示例 |
---|---|---|
math.sinh(x) |
双曲正弦((eˣ - e⁻ˣ)/2) | math.sinh(0) → 0.0 |
math.cosh(x) |
双曲余弦((eˣ + e⁻ˣ)/2) | math.cosh(0) → 1.0 |
math.tanh(x) |
双曲正切(sinh (x)/cosh (x)) | math.tanh(0) → 0.0 |
七、注意事项与常见错误
-
参数类型与范围:
- 多数函数要求输入为实数(
int
或float
),输入复数会抛TypeError
(需用cmath
模块)。 - 对数函数(
log
、log10
等)和平方根函数(sqrt
)的输入必须为正数,否则抛ValueError
。
- 多数函数要求输入为实数(
-
浮点数精度问题:
- 浮点数计算存在精度误差(如
0.1 + 0.2 = 0.30000000000000004
),判断相等时需用math.isclose()
而非==
。
print(0.1 + 0.2 == 0.3) # 输出:False(精度误差) print(math.isclose(0.1 + 0.2, 0.3)) # 输出:True(允许误差范围内)
- 浮点数计算存在精度误差(如
-
与内置函数的选择:
- 简单运算(如
2**3
、abs(-5)
)用内置函数更高效; - 复杂运算(如三角函数、阶乘)用
math
模块更可靠。
- 简单运算(如
八、总结
math
模块是 Python 科学计算的基础工具,提供了从基础运算到高级数学函数的完整支持,核心应用场景包括:- 工程计算(如圆的面积、三角形角度);
- 数据分析(如对数转换、概率计算);
- 科学模拟(如三角函数建模、指数增长模型)。
掌握
math
模块的常用函数(取整、幂运算、对数、三角函数)和常量(pi
、e
),能大幅提升数学计算的效率和精度。需注意其浮点数特性和参数范围限制,避免因类型错误或精度问题导致的计算偏差。