使用 NumPy 生成均匀分布的随机数


高斯分布,也称为正态分布,在统计分析和数据建模中常用。它以其熟悉的钟形曲线为特征,表示实值随机变量的连续概率分布。其钟形曲线特性使其成为模拟现实世界现象的常用工具。

random 模块生成一组从正态分布中抽取的伪随机数,并指定均值和标准差。

语法

numpy.random.uniform(low=0.0, high=1.0, size=None)

参数

low :它接受浮点数或数组作为参数,表示可以生成的最小值。默认值为 0。

high:与 low 非常相似,但默认值为 1。

size :它接受整数或整数元组作为参数,并确定要生成的随机数的数量。

示例

以下示例演示了如何生成具有默认下限和上限(0 和 1)的随机数。

算法

  • 将 numpy 库导入为 nmp。

  • 使用 numpy.random.uniform 函数,不指定显式下限和上限。

  • 将 size 参数指定为 5,以从均匀分布中生成五个随机数。

  • 将生成的随机数存储在单独的变量中。

import numpy as nmp

# Generate five random numbers from the uniform distribution
random_numbers = nmp.random.uniform(size=5)

# Print the generated random numbers
print("The Random Generated Numbers Are:", random_numbers)

输出

The Random Generated Numbers Are: [0.16686196 0.00839822 0.70146929 0.98215339 0.65254042]

示例

以下代码说明了如何使用 numpy 从均匀分布中生成具有特定范围的 10 个随机数。

import numpy as np

# Set the lower and upper bounds
lower_bound = 10  # Lower bound of the distribution
upper_bound = 20  # Upper bound of the distribution

# Generate five random numbers from the uniform distribution
random_numbers = np.random.uniform(low=lower_bound, high=upper_bound, size=10)

# Print the generated random numbers
print("Generated Random Numbers:", random_numbers)

输出

Generated Random Numbers: [12.17244749 19.45438526 17.23474221 12.62434952 
14.93329819 19.24373114 14.46020672 10.5430179  13.23576976 16.82255347]

示例

在本例中,我们将使用 NumPy 的均匀分布生成一个 2D 随机数数组,并使用自定义范围。

算法

  • 导入 numpy 库。

  • 设置均匀分布所需的上下限值。

  • 将上下限值作为参数传递,并指定参数的大小。

  • 将生成的随机数存储在单独的变量中。

import numpy as nmpy

# Set the lower and upper bounds
lower_bound = 0 
upper_bound = 100 

# Generate a 2D array of random numbers from the uniform distribution
random_numbers = nmpy.random.uniform(low=lower_bound, high=upper_bound, size=
(3, 5))

# Print the generated random numbers
print("The 2D array Randomly generated Numbers:")
print(random_numbers)

输出

The 2D array Randomly generated Numbers:
[[34.9530181  47.99901914 80.16861203  5.86164601 24.51089145]
 [87.87714454 79.73164792 17.19521485 67.10860954 54.12845578]
 [75.46746683 55.00061495 93.79876457 74.6587852  33.00568042]]

结论

NumPy 是一个强大的工具,开发人员可以使用它在 Python 中从均匀分布生成随机数,这些随机数可用于各种应用、模拟和为测试用例生成随机数据点,这通常用于为机器学习应用程序创建合成数据以创建随机输入。

更新于: 2023年8月10日

848 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.