math与random模块
math 和 random 是 Python 标准库中处理数学运算和随机数的核心模块。math 提供浮点数数学函数,random 提供伪随机数生成。两者在科学计算、游戏开发、模拟仿真、密码学(仅 random 的 SystemRandom)等领域广泛使用。
math模块
常量:
import math
print math.pi # 3.141592653589793
print math.e # 2.718281828459045
基本运算:
import math
print math.sqrt(16) # 4.0 —— 平方根
print math.pow(2, 10) # 1024.0 —— 幂运算
print math.exp(1) # 2.718... —— e^x
print math.log(math.e) # 1.0 —— 自然对数
print math.log10(100) # 2.0 —— 常用对数
print math.log(8, 2) # 3.0 —— 以 2 为底的对数
取整:
import math
print math.ceil(4.2) # 5.0 —— 向上取整
print math.floor(4.8) # 4.0 —— 向下取整
print math.trunc(4.8) # 4 —— 截断小数
print round(4.5) # 5.0 —— 四舍五入(内置函数)
注意 round() 是内置函数,不是 math 模块的。Python 2 中 round(2.5) 返回 3.0,round(3.5) 也返回 4.0(银行家舍入法的变体,实际上 Python 2 的 round 是向远离零的方向舍入到偶数)。
三角函数:
import math
print math.sin(math.pi / 2) # 1.0
print math.cos(0) # 1.0
print math.tan(math.pi / 4) # 1.0
print math.degrees(math.pi) # 180.0 —— 弧度转角度
print math.radians(180) # 3.141... —— 角度转弧度
其他函数:
import math
print math.fabs(-5) # 5.0 —— 绝对值(浮点)
print math.factorial(5) # 120 —— 阶乘
print math.gcd(48, 18) # 6 —— 最大公约数(Python 2.7 没有,Python 3.5+)
print math.hypot(3, 4) # 5.0 —— 直角三角形斜边
Python 2.7 没有 math.gcd,可以用 fractions.gcd:
from fractions import gcd
print gcd(48, 18) # 6
random模块
基本随机数:
import random
print random.random() # [0.0, 1.0) 之间的浮点数
print random.uniform(1, 10) # [1, 10] 之间的浮点数
print random.randint(1, 10) # [1, 10] 之间的整数(包含两端)
print random.randrange(10) # [0, 10) 之间的整数
print random.randrange(1, 10, 2) # [1, 10) 之间的奇数
序列操作:
import random
items = [1, 2, 3, 4, 5]
print random.choice(items) # 随机选择一个元素
print random.sample(items, 3) # 随机选择 3 个不重复的元素
random.shuffle(items) # 原地打乱顺序
print items # 随机排列
种子与可重复性:
import random
random.seed(42) # 设置种子
print random.random() # 0.6394267984578837
random.seed(42) # 相同种子
print random.random() # 0.6394267984578837 —— 相同结果
设置种子后,随机序列可重复,这在调试和测试时很有用。
实际应用
计算距离:
import math
def distance(p1, p2):
return math.sqrt(
(p1[0] - p2[0]) ** 2 +
(p1[1] - p2[1]) ** 2
)
print distance((0, 0), (3, 4)) # 5.0
随机密码生成:
import random
import string
def generate_password(length=12):
chars = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(chars) for _ in range(length))
print generate_password()
# aB3#kL9$mP2@
蒙特卡洛模拟:
import random
import math
def estimate_pi(n=1000000):
inside = 0
for _ in range(n):
x, y = random.random(), random.random()
if x * x + y * y <= 1:
inside += 1
return 4.0 * inside / n
print estimate_pi() # 约 3.141...(精度随 n 增加)
正态分布:
import random
# 均值为 0,标准差为 1 的正态分布
print random.gauss(0, 1)
# 生成多个样本
samples = [random.gauss(100, 15) for _ in range(1000)]
print sum(samples) / len(samples) # 约 100
密码学安全随机数
random 模块的随机数是伪随机的,不适用于密码学。密码学安全随机数用 random.SystemRandom:
import random
secure_random = random.SystemRandom()
print secure_random.random()
print secure_random.randint(1, 100)
SystemRandom 使用操作系统的熵源(如 /dev/urandom),适合生成密钥、令牌等安全敏感数据。
与 NumPy 的关系
对于大规模数值计算,NumPy 比标准库的 math 和 random 快得多:
# 标准库:逐个计算
import math, random
result = [math.sqrt(random.random()) for _ in range(1000000)]
# NumPy:向量化计算(更快)
import numpy as np
result = np.sqrt(np.random.random(1000000))
标准库的 math 和 random 适合简单场景,大规模科学计算应使用 NumPy。