Created
March 4, 2024 06:40
-
-
Save jeferwang/14534691907a2a8ba0517460f4c359e6 to your computer and use it in GitHub Desktop.
使用BoxMuller算法生成符合正态分布随机数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 从这抄的 | |
# https://blog.csdn.net/Yonggie/article/details/97404027 | |
import math | |
from random import random | |
import matplotlib.pyplot as plt | |
# mu:均值/期望 | |
# sigma:标准差 | |
def Generate(mu, sigma): | |
data = [] | |
for i in range(10000): | |
data.append( | |
mu | |
+ sigma | |
* (math.sqrt(-2 * math.log(random())) * math.sin(2 * math.pi * random())) | |
) | |
plt.figure() | |
plt.hist(data, bins=50) | |
plt.show() | |
exit(0) | |
if __name__ == "__main__": | |
# Generate(0,1) | |
# 标准差0.25表示生成的随机数大多数落在[-1,1]区间内 | |
Generate(0,0.25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment