利用numpy.random.randn()函数生成服从正态分布的随机数集合
发布时间:2023-12-24 09:42:32
numpy.random.randn()函数是numpy库中的一个函数,用于生成服从标准正态分布(均值为0,方差为1)的随机数集合。它可以接受一个整数n作为参数,表示生成n个随机数。
使用例子如下:
首先,我们需要导入numpy库:
import numpy as np
然后,我们可以使用numpy.random.randn()函数生成服从正态分布的随机数。
random_numbers = np.random.randn(1000)
上述代码将生成一个包含1000个服从标准正态分布的随机数的一维数组random_numbers。
我们可以验证一下这个数组的均值和方差是否接近于0和1:
mean = np.mean(random_numbers)
variance = np.var(random_numbers)
print("Mean:", mean)
print("Variance:", variance)
输出结果应该接近于:
Mean: 0.0 Variance: 1.0
接着,我们可以对这个随机数数组进行一些常见的操作。例如,我们可以计算数组的最大值、最小值、中位数和四分位数:
maximum = np.max(random_numbers)
minimum = np.min(random_numbers)
median = np.median(random_numbers)
first_quartile = np.percentile(random_numbers, 25)
third_quartile = np.percentile(random_numbers, 75)
print("Maximum:", maximum)
print("Minimum:", minimum)
print("Median:", median)
print("First Quartile:", first_quartile)
print("Third Quartile:", third_quartile)
我们还可以使用matplotlib库将这个随机数数组进行可视化,以直观地呈现正态分布的特性:
import matplotlib.pyplot as plt
plt.hist(random_numbers, bins='auto')
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Histogram of Random Numbers')
plt.show()
上述代码将绘制出一个直方图,其中x轴表示随机数的值,y轴表示该值出现的频率。
通过以上的例子,我们可以通过numpy.random.randn()函数轻松地生成服从正态分布的随机数集合,并利用numpy和matplotlib库进行一系列常见的统计分析和可视化操作。
