CodeWalk

random与math模块的常用函数详解

作者:孤独的心 · 2026-05-30 12:55

请介绍Python random模块和math模块的常用函数,包括随机数生成、统计分布随机抽样,以及数学运算函数。

回答

孤独的心

random模块

  • random.random() — [0.0, 1.0)浮点数
  • random.randint(a, b) — [a, b]整数
  • random.choice(seq) — 序列中随机选一个
  • random.choices(population, weights=None, k=1) — 带权重的随机选择
  • random.sample(population, k) — 不重复随机抽样
  • random.shuffle(lst) — 原地打乱列表
  • random.gauss(mu, sigma) — 高斯分布随机数
  • random.seed(n) — 设置随机种子,使结果可重现

math模块

  • math.ceil(x) / math.floor(x) — 向上/向下取整
  • math.sqrt(x) — 平方根
  • math.pow(x, y) — x的y次幂(返回浮点数)
  • math.log(x, base) — 对数,默认自然对数
  • math.sin() / math.cos() / math.tan() — 三角函数
  • math.pi / math.e — 常量π和e
  • math.factorial(n) — 阶乘
  • math.gcd(a, b) — 最大公约数
  • math.isclose(a, b, rel_tol=1e-9) — 浮点数相等比较(重要!避免==