math模块 — 数学函数

Python标准库精讲专题 · 数字与数学篇 · 掌握数学函数工具

专题:Python标准库精讲系统学习

关键词:Python, 标准库, math, 数学函数, 三角函数, 对数, 指数, pi, sqrt, sin, cos, ceil, floor

一、math模块概述

math模块是Python标准库中提供数学运算功能的核心模块。它封装了C语言标准数学库(libm)的接口,为开发者提供了高效、可靠的数学计算能力。math模块主要包含两类功能:数学常数和数学函数。所有函数均基于浮点数运算,返回值为float类型。

使用math模块非常简单,只需在代码起始处执行导入操作即可。该模块是Python标准库的一部分,无需额外安装。

基本导入方式

import math # 查看模块中的所有可用函数和常数 print(dir(math)) # 输出中将包含 pi, e, sin, cos, sqrt 等

适用场景

math模块广泛应用于科学计算、数据分析、图形处理、物理模拟、工程计算以及各种需要数学运算的场景。对于复数运算,Python提供了专用的cmath模块;而对于更高级的科学计算,可基于math模块构建或结合NumPy等第三方库使用。

注意:math模块的所有三角函数均使用弧度制而非角度制。如果需要使用角度制,需要先用radians()方法将角度转换为弧度,或使用degrees()将弧度转换为角度。此外,math模块不支持复数运算,复数运算请使用cmath模块。

二、数学常数 — pi、e、tau、inf、nan

math模块提供了一系列精确的数学常数,这些常数是科学计算中的基础工具。开发者无需手动定义这些常数,直接使用即可保证精度。

常用常数一览

常数说明
math.pi3.141592653589793圆周率 π,圆的周长与直径之比
math.e2.718281828459045自然对数的底数 e
math.tau6.283185307179586圆周率 τ = 2π,完整的圆周长与半径之比
math.infinf正无穷大浮点数
math.nannan非数字(Not a Number),表示无效或未定义的数学结果

代码示例

import math # 圆周率 pi print(f"pi = {math.pi}") # pi = 3.141592653589793 # 自然对数底数 e print(f"e = {math.e}") # e = 2.718281828459045 # tau = 2 * pi print(f"tau = {math.tau}") # tau = 6.283185307179586 print(f"tau == 2 * pi: {math.tau == 2 * math.pi}") # True # 无穷大 print(f"inf = {math.inf}") # inf print(f"inf > 9999999999: {math.inf > 9999999999}") # True # 非数字 print(f"nan = {math.nan}") # nan print(f"math.isnan(math.nan): {math.isnan(math.nan)}") # True

提示:math.inf(无穷大)可用于初始化比较算法中的最小值变量或表示无界值。math.nan通常表示非法数学操作(如0/0)的结果。注意,nan与任何值(包括它自身)的比较结果均为False,必须使用math.isnan()来判断。

import math # nan 的特殊性质 print(math.nan == math.nan) # False —— nan 不等于任何值,包括它自己 print(math.isnan(math.nan)) # True —— 必须使用 isnan 判断 # inf 的比较 print(math.inf > 1e308) # True print(-math.inf < -1e308) # True

三、数论与表示函数

数论与表示函数是math模块中最常用的一类工具函数,涵盖了取整、阶乘、最大公约数、组合数等基础数学运算。这些函数在处理日常数学计算时极为高效。

取整函数:ceil、floor、trunc

函数说明示例
math.ceil(x)返回大于或等于x的最小整数(向上取整)ceil(3.1) = 4
math.floor(x)返回小于或等于x的最大整数(向下取整)floor(3.9) = 3
math.trunc(x)截断小数部分,返回整数部分(向零取整)trunc(-3.7) = -3
import math x = 3.14159 print(f"ceil({x}) = {math.ceil(x)}") # 4 print(f"floor({x}) = {math.floor(x)}") # 3 print(f"trunc({x}) = {math.trunc(x)}") # 3 y = -3.14159 print(f"ceil({y}) = {math.ceil(y)}") # -3 print(f"floor({y}) = {math.floor(y)}") # -4 print(f"trunc({y}) = {math.trunc(y)}") # -3

绝对值与符号函数

import math # fabs —— 浮点数绝对值 print(f"fabs(-5.5) = {math.fabs(-5.5)}") # 5.5 print(f"fabs(3.14) = {math.fabs(3.14)}") # 3.14 # fmod —— 浮点数取模 print(f"fmod(10.5, 3.2) = {math.fmod(10.5, 3.2)}") # 0.8999999999999995

阶乘与组合数学

import math # factorial —— 阶乘(n!) print(f"5! = {math.factorial(5)}") # 120 print(f"10! = {math.factorial(10)}") # 3628800 # comb(n, k) —— 组合数 C(n, k) print(f"C(10, 3) = {math.comb(10, 3)}") # 120 print(f"C(52, 5) = {math.comb(52, 5)}") # 2598960 (德州扑克组合数) # perm(n, k) —— 排列数 P(n, k) print(f"P(10, 3) = {math.perm(10, 3)}") # 720

最大公约数与最小公倍数

import math # gcd —— 最大公约数 print(f"gcd(12, 8) = {math.gcd(12, 8)}") # 4 print(f"gcd(24, 36, 48) = {math.gcd(24, 36, 48)}") # 12 # lcm —— 最小公倍数 (Python 3.9+) print(f"lcm(12, 8) = {math.lcm(12, 8)}") # 24 print(f"lcm(6, 8, 12) = {math.lcm(6, 8, 12)}") # 24

浮点数判断函数

import math # isfinite —— 判断是否为有限数 print(f"isfinite(100) = {math.isfinite(100)}") # True print(f"isfinite(inf) = {math.isfinite(math.inf)}") # False # isinf —— 判断是否为无穷大 print(f"isinf(inf) = {math.isinf(math.inf)}") # True print(f"isinf(-inf) = {math.isinf(-math.inf)}") # True # isnan —— 判断是否为非数字 print(f"isnan(nan) = {math.isnan(math.nan)}") # True print(f"isnan(0/0) = {math.isnan(float('nan'))}") # True

实用技巧:math.comb()和math.perm()是Python 3.8新增的函数,非常适合概率统计和组合优化场景。math.lcm()是Python 3.9新增,用于计算最小公倍数。这些函数在高版本Python中有效,使用时注意版本兼容性。

四、幂与对数函数

幂函数与对数函数是数学计算中的核心组成部分,math模块提供了高精度的实现。这些函数覆盖了从基础的开平方、乘方到各种底数的对数运算。

幂函数:pow与sqrt

import math # sqrt —— 平方根 print(f"sqrt(16) = {math.sqrt(16)}") # 4.0 print(f"sqrt(2) = {math.sqrt(2)}") # 1.4142135623730951 # pow —— 幂运算(浮点数版本) print(f"pow(2, 10) = {math.pow(2, 10)}") # 1024.0 print(f"pow(16, 0.5) = {math.pow(16, 0.5)}") # 4.0 (相当于sqrt) print(f"pow(3, 1.5) = {math.pow(3, 1.5)}") # 5.196152422706632 # 内置 pow 与 math.pow 的区别 print(f"内置 pow(2, 3) = {pow(2, 3)}") # 8 print(f"math.pow(2, 3) = {math.pow(2, 3)}") # 8.0 (总是返回float) # 内置 pow 支持取模 print(f"pow(2, 10, 7) = {pow(2, 10, 7)}") # 2 (等价于 2^10 % 7)

指数函数:exp与expm1

import math # exp —— e 的 x 次幂 print(f"exp(1) = {math.exp(1)}") # 2.718281828459045 (等于 e) print(f"exp(0) = {math.exp(0)}") # 1.0 print(f"exp(5) = {math.exp(5)}") # 148.4131591025766 # expm1 —— e^x - 1(高精度,避免x很小时的舍入误差) print(f"expm1(1e-10) = {math.expm1(1e-10)}") # 1.00000000005e-10 print(f"exp(1e-10) - 1 = {math.exp(1e-10) - 1}") # 1.000000082740371e-10

对数函数:log、log2、log10

import math # log —— 自然对数(底数为 e) print(f"log(e) = {math.log(math.e)}") # 1.0 print(f"log(100) = {math.log(100)}") # 4.605170185988092 # log(x, base) —— 指定底数的对数 print(f"log(100, 10) = {math.log(100, 10)}") # 2.0 print(f"log(8, 2) = {math.log(8, 2)}") # 3.0 # log2 —— 以 2 为底的对数 print(f"log2(1024) = {math.log2(1024)}") # 10.0 print(f"log2(8) = {math.log2(8)}") # 3.0 # log10 —— 以 10 为底的对数 print(f"log10(1000) = {math.log10(1000)}") # 3.0 print(f"log10(1e6) = {math.log10(1e6)}") # 6.0 # log1p —— ln(1+x) 的高精度版本 x = 1e-15 print(f"log1p({x}) = {math.log1p(x)}") # 1e-15 (高精度) print(f"log(1 + {x}) = {math.log(1 + x)}") # 1.1102230246251565e-15 (舍入误差)

精度对比:当x非常接近0时,使用math.log1p(x)比math.log(1 + x)精度更高;类似地,math.expm1(x)比math.exp(x) - 1精度更高。这是因为浮点运算在加减非常接近的值时会产生舍入误差。在金融计算(如复利计算)和物理模拟中,使用这些高精度版本非常重要。

实际应用:信息论中的信息量计算

import math # 计算信息熵(香农熵) def entropy(probabilities): return -sum(p * math.log2(p) for p in probabilities if p > 0) # 以掷硬币为例 fair_coin = [0.5, 0.5] biased_coin = [0.9, 0.1] print(f"公平硬币的熵: {entropy(fair_coin):.4f} 比特") # 1.0000 print(f"偏置硬币的熵: {entropy(biased_coin):.4f} 比特") # 0.4690

五、三角函数

math模块提供了标准的三角函数实现,包括正弦、余弦、正切及其反函数。所有三角函数均使用弧度制作为角度单位,这是数学计算中的标准惯例。

基本三角函数

import math # sin、cos、tan —— 基本三角函数(参数为弧度) angle = math.pi / 4 # 45度 print(f"sin(pi/4) = {math.sin(angle):.6f}") # 0.707107 (sqrt(2)/2) print(f"cos(pi/4) = {math.cos(angle):.6f}") # 0.707107 (sqrt(2)/2) print(f"tan(pi/4) = {math.tan(angle):.6f}") # 1.000000 # 验证恒等式 sin^2 + cos^2 = 1 s = math.sin(angle) c = math.cos(angle) print(f"sin^2 + cos^2 = {s**2 + c**2:.1f}") # 1.0

反三角函数

import math # asin、acos、atan —— 反三角函数(返回弧度值) x = 0.7071067811865476 print(f"asin({x}) = {math.asin(x):.4f} rad") # 0.7854 rad (约45度) print(f"acos({x}) = {math.acos(x):.4f} rad") # 0.7854 rad (约45度) print(f"atan(1) = {math.atan(1):.4f} rad") # 0.7854 rad (约45度) # 验证:asin(sin(theta)) = theta theta = 0.8 print(f"asin(sin({theta})) = {math.asin(math.sin(theta)):.4f}") # 0.8000

atan2 —— 最实用的反三角函数

import math # atan2(y, x) —— 返回点(x,y)与x轴正方向之间的夹角 # 不同于atan(y/x),atan2能正确处理四个象限 print(f"atan2(1, 0) = {math.atan2(1, 0):.4f}") # 1.5708 (90度) print(f"atan2(0, 1) = {math.atan2(0, 1):.4f}") # 0.0000 (0度) print(f"atan2(-1, 0) = {math.atan2(-1, 0):.4f}") # -1.5708 (-90度) print(f"atan2(1, -1) = {math.atan2(1, -1):.4f}") # 2.3562 (135度) # atan(y/x) 不能正确处理第二象限 print(f"atan(1/(-1)) = {math.atan(1/(-1)):.4f}") # -0.7854 (-45度, 错误!)

核心区别:math.atan2(y, x)与math.atan(y/x)的区别在于,atan2可以正确处理四个象限的角度,返回范围是[-π, π];而atan的返回范围仅为[-π/2, π/2]。在游戏开发、机器人导航、GPS坐标计算中,atan2是计算方向角的标准方法。

实际应用:计算两点间距离和方位角

import math def distance_and_bearing(lat1, lon1, lat2, lon2): # 将经纬度转换为弧度 lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) # 哈弗辛公式 (Haversine formula) 计算距离 dlat = lat2 - lat1 dlon = lon2 - lon1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) distance = 6371 * c # 地球半径6371km # 计算方位角 bearing = math.atan2( math.sin(dlon) * math.cos(lat2), math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dlon) ) bearing = math.degrees(bearing) bearing = (bearing + 360) % 360 return distance, bearing # 北京到上海的距离和方位 dist, bear = distance_and_bearing(39.9042, 116.4074, 31.2304, 121.4737) print(f"北京-上海距离: {dist:.1f} km") # 约 1067 km print(f"方位角: {bear:.1f}°") # 约 158° (东南方向)

六、双曲函数

双曲函数是数学中一类重要的超越函数,与指数函数密切相关。它们在物理学(如悬链线方程)、工程学和深度学习(如tanh激活函数)中有着广泛的应用。math模块提供了完整的双曲函数及其反函数支持。

双曲函数的基本关系

双曲函数通过指数函数定义:sinh(x) = (e^x - e^(-x))/2,cosh(x) = (e^x + e^(-x))/2,tanh(x) = sinh(x)/cosh(x)。它们满足类似三角函数的恒等式,如cosh^2(x) - sinh^2(x) = 1。

import math x = 1.0 # 双曲函数 print(f"sinh({x}) = {math.sinh(x):.6f}") # 1.175201 print(f"cosh({x}) = {math.cosh(x):.6f}") # 1.543081 print(f"tanh({x}) = {math.tanh(x):.6f}") # 0.761594 # 验证恒等式 cosh^2 - sinh^2 = 1 sh = math.sinh(x) ch = math.cosh(x) print(f"cosh^2 - sinh^2 = {ch**2 - sh**2:.1f}") # 1.0 # 反双曲函数 print(f"asinh(1.175201) = {math.asinh(1.175201):.6f}") # 1.000000 print(f"acosh(1.543081) = {math.acosh(1.543081):.6f}") # 1.000000 print(f"atanh(0.761594) = {math.atanh(0.761594):.6f}") # 1.000000

实际应用:深度学习中的tanh激活函数

import math # tanh 常用作神经网络的激活函数 def tanh_activation(x): return math.tanh(x) # 可视化 tanh 在不同输入下的输出 for x in [-3, -2, -1, -0.5, 0, 0.5, 1, 2, 3]: print(f"tanh({x:+.0f}) = {tanh_activation(x):+.6f}") # tanh 输出范围在 (-1, 1) 之间 # 相比 sigmoid 函数,tanh 的梯度更大,收敛更快

实际应用:悬链线方程

import math # 悬链线(如电线、铁链自然下垂的形状) # y = a * cosh(x/a) def catenary(x, a=1.0): return a * math.cosh(x / a) # 计算悬链线在 x=0 和 x=1 处的高度 print(f"悬链线在 x=0 处高度: {catenary(0):.4f}") # 1.0000 print(f"悬链线在 x=1 处高度: {catenary(1):.4f}") # 1.5431

七、角度转换与特殊函数

math模块提供了角度单位转换函数以及一些在概率统计、物理学中常用的特殊函数。这些函数极大地简化了数学计算中的单位转换工作,并为高级数学运算提供了基础支持。

角度转换:degrees与radians

import math # radians —— 将角度转换为弧度 print(f"radians(180) = {math.radians(180):.4f}") # 3.1416 (pi) print(f"radians(90) = {math.radians(90):.4f}") # 1.5708 (pi/2) print(f"radians(45) = {math.radians(45):.4f}") # 0.7854 (pi/4) # degrees —— 将弧度转换为角度 print(f"degrees(pi) = {math.degrees(math.pi):.4f}") # 180.0000 print(f"degrees(pi/2) = {math.degrees(math.pi/2):.4f}") # 90.0000 print(f"degrees(1) = {math.degrees(1):.4f}") # 57.2958
import math # 实用举例:计算30度、60度的正弦值 print(f"sin(30°) = {math.sin(math.radians(30)):.4f}") # 0.5000 print(f"sin(60°) = {math.sin(math.radians(60)):.4f}") # 0.8660 print(f"cos(45°) = {math.cos(math.radians(45)):.4f}") # 0.7071

误差函数:erf与erfc

误差函数(erf)和补余误差函数(erfc)在概率论、统计学和偏微分方程中有重要应用。erf(x)是标准正态分布累积分布函数的核心组成部分。

import math # erf —— 误差函数 # 公式: erf(x) = (2/sqrt(pi)) * ∫_0^x e^(-t^2) dt print(f"erf(0) = {math.erf(0):.4f}") # 0.0000 print(f"erf(1) = {math.erf(1):.4f}") # 0.8427 print(f"erf(inf) = {math.erf(math.inf):.4f}") # 1.0000 print(f"erf(-inf) = {math.erf(-math.inf):.4f}") # -1.0000 # erfc —— 补余误差函数,erfc(x) = 1 - erf(x) print(f"erfc(1) = {math.erfc(1):.6f}") # 0.157299 print(f"erfc(3) = {math.erfc(3):.10f}") # 0.0000220905 # 实际应用:计算正态分布的累积分布函数 def normal_cdf(x, mu=0, sigma=1): return 0.5 * (1 + math.erf((x - mu) / (sigma * math.sqrt(2)))) # 标准正态分布在各个分位点的累积概率 for z in [-2, -1, 0, 1, 2]: p = normal_cdf(z) print(f"P(Z <= {z:+.0f}) = {p:.4f}")

伽马函数:gamma与lgamma

伽马函数是阶乘的推广,定义在所有正实数上。对于正整数n,gamma(n) = (n-1)!。gamma函数在概率论(如伽马分布)、数论和组合数学中广泛应用。

import math # gamma —— 伽马函数 print(f"gamma(1) = {math.gamma(1):.1f}") # 1.0 (0! = 1) print(f"gamma(2) = {math.gamma(2):.1f}") # 1.0 (1! = 1) print(f"gamma(5) = {math.gamma(5):.1f}") # 24.0 (4! = 24) # 验证 gamma(n) = (n-1)! for n in range(1, 8): assert math.gamma(n) == math.factorial(n - 1) print("gamma(n) == (n-1)! 验证通过!") # lgamma —— 伽马函数的自然对数(高精度) print(f"lgamma(100) = {math.lgamma(100):.6f}") # 359.134206 print(f"log(gamma(100)) = {math.log(math.gamma(100)):.6f}") # 359.134206

计算技巧:lgamma(x)返回ln(|gamma(x)|),在计算非常大的阶乘时,直接使用lgamma可以避免数值溢出。例如,gamma(200)的值远超浮点数的表示范围,但lgamma(200)可以精确计算。这对于统计学中的极大似然估计和贝叶斯计算非常有用。

import math # 使用 lgamma 计算大数的阶乘对数 def log_factorial(n): return math.lgamma(n + 1) print(f"log(100!) = {log_factorial(100):.6f}") print(f"log(1000!) = {log_factorial(1000):.6f}") # 计算大数的二项式系数对数 def log_comb(n, k): return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) # C(1000, 500) 的对数 print(f"log(C(1000, 500)) = {log_comb(1000, 500):.6f}")

hypot —— 欧几里得范数

import math # hypot —— 计算 sqrt(x^2 + y^2),避免中间溢出 print(f"hypot(3, 4) = {math.hypot(3, 4)}") # 5.0 print(f"hypot(1, 1) = {math.hypot(1, 1)}") # 1.4142135623730951 # 支持多个参数 (Python 3.8+) print(f"hypot(1, 1, 1) = {math.hypot(1, 1, 1)}") # 1.7320508075688772

八、核心总结

知识脉络

math模块是Python标准库中最重要的基础模块之一,按功能可分为五大类别:数学常数(pi、e、tau、inf、nan)、数论函数(ceil、floor、gcd、lcm、factorial、comb、perm)、幂与对数函数(pow、sqrt、exp、log、log2、log10)、三角函数及其反函数(sin、cos、tan、asin、acos、atan、atan2)、双曲函数(sinh、cosh、tanh及相关反函数),以及特殊函数(degrees、radians、erf、erfc、gamma、lgamma)。

关键要点

学习路径建议

学习建议:math模块虽然功能丰富,但不必一次性全部掌握。在日常编程中,最常用的不过十余个函数。建议先熟悉ceil、floor、sqrt、pow、sin、cos、tan、atan2、log、exp这十大核心函数,再根据实际需求逐步扩展。遇到具体数学运算问题时,多查阅官方文档,通过dir(math)和help(math.xxx)随时获取帮助。

类别核心函数/常数推荐指数
常数pi, e, inf★★★★★
取整ceil, floor, trunc★★★★★
数论gcd, lcm, factorial, comb★★★★
幂与对sqrt, pow, exp, log, log2, log10★★★★★
三角函数sin, cos, tan, atan2★★★★★
双曲函数tanh, sinh, cosh★★★
角度转换degrees, radians★★★★
特殊函数erf, gamma, lgamma, hypot★★★