Python内置模块之math数学运算全面解析
更新时间:2026年08月04日 08:56:59 作者:星河耀银海
本文将带你全面掌握Python中的math模块,从常量pi和e到取整、阶乘、三角函数等常用函数一应俱全,并精选Top10最常用函数,助你高效处理日常和科学计算,告别数学运算难题
一、开篇:Python的数学工具箱
math模块是Python最基础的内置模块之一,提供了C标准库中定义的数学函数。从三角函数到对数,从取整到阶乘,它涵盖了日常和科学计算中的大部分需求。
导入和使用:
import math # math模块提供: # - 数学常量:pi, e, tau, inf, nan # - 数值运算:取整、绝对值、阶乘、组合数 # - 幂和对数:sqrt, pow, exp, log, log2, log10 # - 三角函数:sin, cos, tan 及其反函数 # - 特殊函数:gcd, lcm, erf, gamma # - 角度转换:degrees, radians
二、数学常量
import math
# 圆周率 π
print(f"π = {math.pi}") # 3.141592653589793
print(f"π/2 = {math.pi / 2}") # 1.5707963267948966
# 自然常数 e
print(f"e = {math.e}") # 2.718281828459045
# 圆的周长与面积
r = 5
circumference = 2 * math.pi * r
area = math.pi * r ** 2
print(f"半径{r}的圆: 周长={circumference:.2f}, 面积={area:.2f}")
# τ (tau) = 2π —— Python 3.6+
print(f"τ = {math.tau}") # 6.283185307179586
# 无穷大和非数字
print(f"无穷大: {math.inf}") # inf
print(f"负无穷: {-math.inf}") # -inf
print(f"非数字: {math.nan}") # nan
# 判断特殊值
print(math.isinf(math.inf)) # True
print(math.isnan(math.nan)) # True
print(math.isfinite(1.0)) # True
print(math.isfinite(math.inf)) # False
# 验证计算
print(1 / math.inf) # 0.0
print(math.inf > 999999999) # True
print(math.nan == math.nan) # False! nan不等于任何值,包括自己
三、数值运算
3.1 取整和截断
import math
# ceil(x) —— 向上取整(往正无穷方向)
print(f"ceil(3.2) = {math.ceil(3.2)}") # 4
print(f"ceil(3.9) = {math.ceil(3.9)}") # 4
print(f"ceil(-3.2) = {math.ceil(-3.2)}") # -3
# floor(x) —— 向下取整(往负无穷方向)
print(f"floor(3.2) = {math.floor(3.2)}") # 3
print(f"floor(3.9) = {math.floor(3.9)}") # 3
print(f"floor(-3.2) = {math.floor(-3.2)}") # -4
# trunc(x) —— 截断小数部分(往0方向)
print(f"trunc(3.7) = {math.trunc(3.7)}") # 3
print(f"trunc(-3.7) = {math.trunc(-3.7)}") # -3
# 💡 ceil vs floor vs trunc vs round 对比
x = -3.7
print(f"x={x}: ceil={math.ceil(x)}, floor={math.floor(x)}, "
f"trunc={math.trunc(x)}, round={round(x)}")
# x=-3.7: ceil=-3, floor=-4, trunc=-3, round=-4
# fabs(x) —— 绝对值(返回float)
print(f"fabs(-5.5) = {math.fabs(-5.5)}") # 5.5
# fmod(x, y) —— 浮点数取余(不同于%)
print(f"fmod(7.5, 2.0) = {math.fmod(7.5, 2.0)}") # 1.5
3.2 阶乘和组合数
import math
# factorial(n) —— n的阶乘(n >= 0)
for n in range(6):
print(f"{n}! = {math.factorial(n)}")
# 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120
# comb(n, k) —— 组合数 C(n,k),从n个中选k个
print(f"C(5,2) = {math.comb(5, 2)}") # 10
# 验证:C(5,2) = 5!/(2!*3!) = 120/(2*6) = 10
# perm(n, k) —— 排列数 P(n,k),从n个中选k个并排序
print(f"P(5,2) = {math.perm(5, 2)}") # 20
# 验证:P(5,2) = 5*4 = 20
# 实际应用:计算中奖概率
def lottery_probability(total, choose):
"""从total个号中选choose个,全中的概率"""
return 1 / math.comb(total, choose)
print(f"双色球红球中奖概率: 1/{math.comb(33, 6)}")
# 双色球红球中奖概率: 1/17721088
四、幂和对数
import math
# sqrt(x) —— 平方根
print(f"sqrt(16) = {math.sqrt(16)}") # 4.0
print(f"sqrt(2) = {math.sqrt(2):.10f}") # 1.4142135624
# pow(x, y) —— x的y次方
print(f"pow(2, 10) = {math.pow(2, 10)}") # 1024.0
# exp(x) —— e的x次方
print(f"exp(1) = {math.exp(1):.6f}") # 2.718282
print(f"exp(2) = {math.exp(2):.6f}") # 7.389056
# 对数
# log(x) —— 自然对数(以e为底)
print(f"log(e) = {math.log(math.e)}") # 1.0
# log2(x) —— 以2为底
print(f"log2(8) = {math.log2(8)}") # 3.0
# log10(x) —— 以10为底
print(f"log10(1000) = {math.log10(1000)}") # 3.0
# log(x, base) —— 以base为底的对数
print(f"log(8, 2) = {math.log(8, 2)}") # 3.0
print(f"log(100, 10) = {math.log(100, 10)}") # 2.0
# 实用函数:计算信息熵(比特)
def entropy_bits(probabilities):
"""计算以2为底的熵"""
return -sum(p * math.log2(p) for p in probabilities if p > 0)
五、三角函数
import math
# 基本三角函数(参数是弧度)
angle = math.pi / 4 # 45度
print(f"sin(45°) = {math.sin(angle):.6f}") # 0.707107
print(f"cos(45°) = {math.cos(angle):.6f}") # 0.707107
print(f"tan(45°) = {math.tan(angle):.6f}") # 1.000000
# 反三角函数
x = 0.5
print(f"asin(0.5) = {math.asin(x):.6f} rad = {math.degrees(math.asin(x)):.1f}°")
# asin(0.5) = 0.523599 rad = 30.0°
# atan2(y, x) —— 计算角度(考虑象限)
print(f"atan2(1, 1) = {math.atan2(1, 1):.6f} rad") # 45°
print(f"atan2(1, -1) = {math.atan2(1, -1):.6f} rad") # 135°
print(f"atan2(-1, -1) = {math.atan2(-1, -1):.6f} rad") # -135°
# 角度弧度转换
print(f"180° = {math.radians(180):.6f} rad") # 3.141593
print(f"π rad = {math.degrees(math.pi):.1f}°") # 180.0°
# 计算两点距离
def distance(x1, y1, x2, y2):
"""计算两点之间的欧几里得距离"""
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print(f"距离: {distance(0, 0, 3, 4)}") # 5.0
六、特殊函数
import math
# gcd(a, b) —— 最大公约数
print(f"gcd(48, 18) = {math.gcd(48, 18)}") # 6
print(f"gcd(17, 31) = {math.gcd(17, 31)}") # 1(互质)
# lcm(a, b) —— 最小公倍数(Python 3.9+)
print(f"lcm(4, 6) = {math.lcm(4, 6)}") # 12
print(f"lcm(12, 18) = {math.lcm(12, 18)}") # 36
# 应用:分数化简
def simplify_fraction(num, den):
"""化简分数"""
g = math.gcd(num, den)
return num // g, den // g
print(f"24/36 化简: {simplify_fraction(24, 36)}") # (2, 3)
# 判断是否为完全平方数
def is_perfect_square(n):
return n >= 0 and math.isqrt(n) ** 2 == n
print(is_perfect_square(25)) # True
print(is_perfect_square(26)) # False
# isclose —— 判断两个数是否接近
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(0.1 + 0.2 == 0.3) # False! 浮点精度问题
七、总结
math模块是Python数学运算的基石。掌握它让你能高效处理日常和科学计算。
最常用Top 10: pi, e, sqrt(), ceil(), floor(), factorial(), gcd(), sin()/cos(), radians()/degrees(), isclose()
需要三角函数→math,需要随机数→random,需要日期时间→datetime。math是纯数学,不涉及概率或日期。
到此这篇关于Python内置模块之math数学运算全面解析的文章就介绍到这了,更多相关Python math模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!


最新评论