在 Python 中生成均值为 0 的随机数,可以使用 random
模块或 numpy.random
模块。以下是几种常见方法:
random
模块(标准库)[-1, 1)
之间的均匀分布随机数import random
# 生成 [-1, 1) 之间的随机数(均匀分布)
rand_num = random.uniform(-1, 1)
print(rand_num)
[-1, 1)
之间的随机整数rand_int = random.randint(-1, 1) # 包含 -1, 0, 1
print(rand_int)
numpy.random
(推荐,适合科学计算)[-1, 1)
之间的均匀分布随机数import numpy as np
# 生成 1 个 [-1, 1) 之间的随机数
rand_num = np.random.uniform(-1, 1)
print(rand_num)
# 生成 10 个 [-1, 1) 之间的随机数
rand_array = np.random.uniform(-1, 1, size=10)
print(rand_array)
# 生成 1 个标准正态分布随机数(均值 0,标准差 1)
rand_gaussian = np.random.randn()
print(rand_gaussian)
# 生成 10 个标准正态分布随机数
rand_gaussian_array = np.random.randn(10)
print(rand_gaussian_array)
mean = 0 # 均值
std = 0.5 # 标准差
rand_custom_gaussian = np.random.normal(mean, std)
print(rand_custom_gaussian)
import matplotlib.pyplot as plt
# 生成 10000 个标准正态分布随机数
data = np.random.randn(10000)
# 绘制直方图
plt.hist(data, bins=50, density=True, alpha=0.7)
plt.title("Standard Normal Distribution (Mean=0, Std=1)")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
输出示例:
https://www.gaussianwaves.com/gaussianwaves/wp-content/uploads/2010/09/randn_histogram.jpg
方法 | 分布类型 | 范围/参数 | 适用场景 |
---|---|---|---|
random.uniform(-1, 1) |
均匀分布 | [-1, 1) |
简单均匀随机数 |
np.random.uniform(-1, 1) |
均匀分布 | [-1, 1) |
高效生成多个随机数 |
np.random.randn() |
标准正态分布 | 均值 0,标准差 1 | 高斯噪声、统计建模 |
np.random.normal(0, std) |
自定义正态分布 | 可调均值/标准差 | 需要特定分布的随机数 |
random.uniform()
或 np.random.uniform()
。np.random.randn()
或 np.random.normal()
。random.randint()
。推荐使用 numpy.random
,因为它更高效且支持批量生成随机数!