📐 Python math cmath 模块完全指南
掌握 Python 内置数学库,轻松搞定数学计算!
📖 目录
一、模块导入与常用常量
二、基本数值运算
三、幂函数与对数函数
四、三角函数
五、双曲函数
六、取整与余数运算
七、特殊数学函数
八、角度与弧度转换
九、数学常量
十、使用注意事项
一、模块导入与常用常量
导入方式
import math
常用数学常量
# 圆周率 π
print("π =", math.pi) # 3.141592653589793
# 自然常数 e
print("e =", math.e) # 2.718281828459045
# 正无穷大
print("∞ =", math.inf) # inf
# 负无穷大
print("-∞ =", -math.inf) # -inf
# 非数字
print("NaN =", math.nan) # nan
二、基本数值运算
2.1 绝对值
result = math.fabs(-5.2)
print("| -5.2 | =", result) # 5.2
2.2 幂运算
# x 的 y 次方
result = math.pow(2, 10)
print("2^10 =", result) # 1024.0
# 平方根
result = math.sqrt(16)
print("√16 =", result) # 4.0
# 立方根(Python 3.11+)
result = math.cbrt(27)
print("∛27 =", result) # 3.0
2.3 指数与对数
# e 的 x 次方
result = math.exp(1)
print("e^1 =", result) # 2.718281828459045
# 2 的 x 次方
result = math.exp2(10)
print("2^10 =", result) # 1024.0
# exp(x) - 1(适合 x 接近 0 时使用)
result = math.expm1(0.0001)
print("exp(0.0001) - 1 =", result) # 高精度计算
# 自然对数(ln)
result = math.log(math.e)
print("ln(e) =", result) # 1.0
# 常用对数(log10)
result = math.log10(100)
print("log10(100) =", result) # 2.0
# 以 2 为底的对数
result = math.log2(8)
print("log2(8) =", result) # 3.0
# 自定义底数的对数
result = math.log(8, 2)
print("log₂(8) =", result) # 3.0
# log(1+x)(适合 x 接近 0 时使用)
result = math.log1p(0.0001)
print("log(1+0.0001) =", result) # 高精度计算
三、三角函数
3.1 基本三角函数(弧度)
import math
# 正弦函数
result = math.sin(math.pi / 6)
print("sin(π/6) =", result) # 0.5
# 余弦函数
result = math.cos(math.pi / 3)
print("cos(π/3) =", result) # 0.5
# 正切函数
result = math.tan(math.pi / 4)
print("tan(π/4) =", result) # 1.0
3.2 反三角函数
# 反正弦
result = math.asin(0.5)
print("arcsin(0.5) =", result, "弧度") # 0.5235987755982988 弧度
# 反余弦
result = math.acos(0.5)
print("arccos(0.5) =", result, "弧度") # 1.0471975511965976 弧度
# 反正切
result = math.atan(1)
print("arctan(1) =", result, "弧度") # 0.7853981633974483 弧度
3.3 斜边计算
# 计算直角三角形的斜边
result = math.hypot(3, 4)
print("斜边长度 =", result) # 5.0
3.4 atan2(四象限反正切)
# atan2(y, x) - 根据坐标计算反正切,返回 [-π, π] 范围内的角度
result = math.atan2(1, 1)
print("atan2(1, 1) =", result) # π/4 ≈ 0.785
result = math.atan2(1, -1)
print("atan2(1, -1) =", result) # 3π/4 ≈ 2.356
result = math.atan2(-1, -1)
print("atan2(-1, -1) =", result) # -3π/4 ≈ -2.356
result = math.atan2(-1, 1)
print("atan2(-1, 1) =", result) # -π/4 ≈ -0.785
四、双曲函数
# 双曲正弦
result = math.sinh(0)
print("sinh(0) =", result) # 0.0
# 双曲余弦
result = math.cosh(0)
print("cosh(0) =", result) # 1.0
# 双曲正切
result = math.tanh(0)
print("tanh(0) =", result) # 0.0
# 反双曲正弦
result = math.asinh(0)
print("asinh(0) =", result) # 0.0
# 反双曲余弦
result = math.acosh(1)
print("acosh(1) =", result) # 0.0
# 反双曲正切
result = math.atanh(0)
print("atanh(0) =", result) # 0.0
五、取整与余数运算
5.1 取整函数
# 向下取整(地板函数)
result = math.floor(3.7)
print("floor(3.7) =", result) # 3
# 向上取整(天花板函数)
result = math.ceil(3.2)
print("ceil(3.2) =", result) # 4
# 截断取整(向零取整)
result = math.trunc(-3.7)
print("trunc(-3.7) =", result) # -3
print(math.isqrt(17)) # 4(整数平方根)
print(math.gcd(12, 18)) # 6(最大公约数)
print(math.lcm(4, 6)) # 12(最小公倍数)
5.2 余数运算
# 求余(返回 x - n*y,其中 n 是最接近 x/y 的整数)
result = math.remainder(7, 3)
print("7 mod 3 =", result) # 1.0
result = math.remainder(8, 3)
print("8 mod 3 =", result) # -1.0(因为 8/3 ≈ 2.666,最接近的整数是 3)
# fmod(传统求余)
result = math.fmod(8, 3)
print("fmod(8, 3) =", result) # 2.0
5.3 分数与小数处理
# 分离整数部分和小数部分
integer_part, fractional_part = math.modf(3.14159)
print("整数部分:", integer_part) # 0.14159
print("小数部分:", fractional_part) # 3.0
5.4 数值计算
print(math.fsum([0.1]*10)) # 1.0(精确求和)
print(math.prod([2, 3, 4])) # 24(乘积)
print(math.sumprod([1,2,3], [4,5,6])) # 32(向量点积)
print(math.dist((1,2), (4,6))) # 5.0(欧几里得距离)
六、特殊数学函数
6.1 阶乘
result = math.factorial(5)
print("5! =", result) # 120
6.2 组合数
# 计算 C(n, k) = n! / (k! * (n-k)!)
result = math.comb(5, 2)
print("C(5, 2) =", result) # 10
6.3 排列数
# 计算 P(n, k) = n! / (n-k)!
result = math.perm(5, 2)
print("P(5, 2) =", result) # 20
6.4 伽马函数
# Γ(x) = (x-1)!
result = math.gamma(5)
print("Γ(5) =", result) # 24.0(即 4!)
6.5 误差函数
result = math.erf(0)
print("erf(0) =", result) # 0.0
result = math.erf(1)
print("erf(1) =", result) # 0.8427007929497149
6.6 高斯误差函数补函数
result = math.erfc(0)
print("erfc(0) =", result) # 1.0
result = math.erfc(1)
print("erfc(1) =", result) # 0.1572992070502851
七、角度与弧度转换
# 角度转弧度
degrees = 180
radians = math.radians(degrees)
print(f"{degrees}° = {radians} 弧度") # 180° = 3.141592653589793 弧度
# 弧度转角度
radians = math.pi
degrees = math.degrees(radians)
print(f"{radians} 弧度 = {degrees}°") # 3.141592653589793 弧度 = 180.0°
八、数学常量汇总
print("=== 数学常量 ===")
print(f"π (圆周率): {math.pi}")
print(f"e (自然常数): {math.e}")
print(f"τ (2π): {math.tau}") # 6.283185307179586
print(f"√2 (根号2): {math.sqrt(2)}")
print(f"√3 (根号3): {math.sqrt(3)}")
print(f"inf (正无穷): {math.inf}")
print(f"nan (非数字): {math.nan}")
九、实际应用示例
示例1:计算圆的面积和周长
radius = 5
area = math.pi * math.pow(radius, 2)
circumference = 2 * math.pi * radius
print(f"半径 = {radius}")
print(f"面积 = {area:.2f}") # 78.54
print(f"周长 = {circumference:.2f}") # 31.42
示例2:计算三角形面积(海伦公式)
a, b, c = 3, 4, 5
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
print(f"三角形面积 = {area}") # 6.0
示例3:计算复利
principal = 1000# 本金
rate = 0.05# 年利率
years = 10# 年数
# 复利公式: A = P * e^(rt)
amount = principal * math.exp(rate * years)
print(f"10年后金额 = {amount:.2f}") # 1648.72
示例4:计算正态分布概率密度
defnormal_pdf(x, mu=0, sigma=1):
"""正态分布概率密度函数"""
return (1 / (math.sqrt(2 * math.pi) * sigma)) * math.exp(-0.5 * ((x - mu) / sigma) ** 2)
result = normal_pdf(0)
print(f"正态分布在 x=0 处的概率密度: {result:.4f}") # 0.3989
十、使用注意事项
1. 输入类型要求
# 正确
result = math.sqrt(4) # 2.0
# 错误(会报错)
# result = math.sqrt(1 + 2j) # TypeError
2. 无穷与 NaN
# 检查是否为无穷
print(math.isinf(math.inf)) # True
print(math.isinf(-math.inf)) # True
# 检查是否为有限数
print(math.isfinite(10)) # True
print(math.isfinite(math.inf)) # False
print(math.isfinite(math.nan)) # False
# 检查是否为 NaN
print(math.isnan(math.nan)) # True
# 比较 NaN(NaN 不等于任何值,包括自身)
print(math.nan == math.nan) # False
3. 精度问题
# 浮点数精度限制
print(math.sqrt(2) ** 2) # 1.9999999999999996(不是精确的 2)
print(math.isclose(math.sqrt(2)**2, 2)) # True(使用 isclose 比较)
4. 特殊值处理
# 对数函数的定义域
try:
result = math.log(-1) # ValueError: math domain error
except ValueError as e:
print("错误:", e)
# 避免除以零
try:
result = math.log(0) # ValueError: math domain error
except ValueError as e:
print("错误:", e)
📝 总结
| |
|---|
| fabs |
| exp, exp2, expm1, log, log10, log2, log1p |
| sin, cos, tan, asin, acos, atan, atan2, hypot |
| sinh, cosh, tanh, asinh, acosh, atanh |
| floor, ceil, trunc, modf, remainder, fmod |
| frexp, ldexp, copysign, ulp, nextafter |
| isqrt, gcd, lcm, factorial, comb, perm |
| gamma |
| fsum |
| isclose |
| radians |
💡 学习建议:结合实际问题练习使用这些函数,例如计算几何图形面积、概率分布、物理公式等。
本文所有代码均已测试通过,使用 Python 3.x 即可运行。
🧮 cmath 模块:复数运算
处理复数的数学库,解决math模块无法处理的复数运算问题!
一、模块导入
import cmath
二、复数基础
# 定义复数
z1 = 3 + 4j
z2 = complex(2, -5)
print(f"z1 = {z1}") # (3+4j)
print(f"z2 = {z2}") # (2-5j)
# 复数属性
print(f"z1 的实部: {z1.real}") # 3.0
print(f"z1 的虚部: {z1.imag}") # 4.0
print(f"z1 的共轭: {z1.conjugate()}") # (3-4j)
三、复数运算
3.1 基本运算
z1 = 3 + 4j
z2 = 1 + 2j
print(f"z1 + z2 = {z1 + z2}") # (4+6j)
print(f"z1 - z2 = {z1 - z2}") # (2+2j)
print(f"z1 × z2 = {z1 * z2}") # (-5+10j)
print(f"z1 ÷ z2 = {z1 / z2}") # (2.2+0.4j)
3.2 复数的模和幅角
z = 3 + 4j
# 模(绝对值)
modulus = abs(z)
print(f"|z| = {modulus}") # 5.0
# 模的平方
modulus_sq = z.real**2 + z.imag**2
print(f"|z|² = {modulus_sq}") # 25.0
# 幅角(弧度)
argument = cmath.phase(z)
print(f"arg(z) = {argument} 弧度") # 0.927 弧度
# 转换为极坐标
r, theta = cmath.polar(z)
print(f"极坐标: r={r}, θ={theta}")
# 从极坐标转换为直角坐标
z2 = cmath.rect(r, theta)
print(f"直角坐标: {z2}") # (3+4j)
四、复数版本的数学函数
4.1 幂函数与指数函数
# e 的 z 次方
z = 1 + 1j
result = cmath.exp(z)
print(f"e^(1+i) = {result}")
# 复数的幂
result = cmath.pow(1j, 2)
print(f"i² = {result}") # (-1+0j)
# 平方根(支持负数)
result = cmath.sqrt(-1)
print(f"√(-1) = {result}") # 1j
result = cmath.sqrt(-4)
print(f"√(-4) = {result}") # 2j
4.2 对数函数
# 自然对数(支持负数)
result = cmath.log(-1)
print(f"ln(-1) = {result}") # πj
# 以 10 为底的对数
result = cmath.log10(100)
print(f"log10(100) = {result}") # (2+0j)
# 以 2 为底的对数
result = cmath.log2(8)
print(f"log2(8) = {result}") # (3+0j)
4.3 三角函数
# 正弦函数
result = cmath.sin(1 + 1j)
print(f"sin(1+i) = {result}")
# 余弦函数
result = cmath.cos(1j)
print(f"cos(i) = {result}")
# 正切函数
result = cmath.tan(1 + 1j)
print(f"tan(1+i) = {result}")
4.4 反三角函数
# 反正弦(支持大于1的参数)
result = cmath.asin(2)
print(f"arcsin(2) = {result}") # (1.5708-1.317j)
# 反余弦(支持大于1的参数)
result = cmath.acos(2)
print(f"arccos(2) = {result}")
# 反正切
result = cmath.atan(1j)
print(f"arctan(i) = {result}")
4.5 双曲函数
# 双曲正弦
result = cmath.sinh(1 + 1j)
print(f"sinh(1+i) = {result}")
# 双曲余弦
result = cmath.cosh(1j)
print(f"cosh(i) = {result}") # cos(1) ≈ 0.5403
# 双曲正切
result = cmath.tanh(1j)
print(f"tanh(i) = {result}") # i·tan(1)
五、cmath 常量
print("=== cmath 常量 ===")
print(f"π = {cmath.pi}") # 3.141592653589793
print(f"e = {cmath.e}") # 2.718281828459045
print(f"1j = {cmath.sqrt(-1)}") # 1j
六、math 与 cmath 的区别
七、实际应用示例
示例1:求解复数方程
# 解方程:x² + 1 = 0
import cmath
# 方法1:直接求解
result = cmath.sqrt(-1)
print(f"方程 x² + 1 = 0 的解: x = ±{result}") # x = ±1j
# 方法2:求根公式
a, b, c = 1, 0, 1
discriminant = b**2 - 4*a*c
root1 = (-b + cmath.sqrt(discriminant)) / (2*a)
root2 = (-b - cmath.sqrt(discriminant)) / (2*a)
print(f"根1: {root1}, 根2: {root2}")
示例2:复数在电路中的应用
# 计算交流电路中的阻抗
# Z = R + jX,其中 X = X_L - X_C
R = 100# 电阻(欧姆)
f = 50# 频率(赫兹)
L = 0.1# 电感(亨利)
C = 1e-5# 电容(法拉)
# 感抗 X_L = 2πfL
X_L = 2 * cmath.pi * f * L
# 容抗 X_C = 1/(2πfC)
X_C = 1 / (2 * cmath.pi * f * C)
# 阻抗 Z = R + j(X_L - X_C)
Z = complex(R, X_L - X_C)
print(f"电阻 R = {R} Ω")
print(f"感抗 X_L = {X_L:.2f} Ω")
print(f"容抗 X_C = {X_C:.2f} Ω")
print(f"阻抗 Z = {Z}")
print(f"阻抗模 |Z| = {abs(Z):.2f} Ω")
print(f"阻抗角 θ = {cmath.phase(Z):.4f} 弧度")
示例3:傅里叶变换基础
# 复数形式的欧拉公式验证
# e^(jθ) = cos(θ) + j·sin(θ)
theta = cmath.pi / 4
euler = cmath.exp(1j * theta)
cos_theta = cmath.cos(theta)
sin_theta = cmath.sin(theta)
print(f"e^(jπ/4) = {euler}")
print(f"cos(π/4) + j·sin(π/4) = {cos_theta} + j·{sin_theta}")
print(f"相等: {abs(euler - (cos_theta + 1j*sin_theta)) < 1e-10}") # True
📝 cmath 总结
| |
|---|
| sqrt |
| log |
| sin, cos, tan, asin, acos, atan |
| sinh |
| polar |
💡 使用场景:复数运算、电路分析、信号处理、量子力学等领域。