Python 中的 random.betavariate() 方法生成一个遵循 Beta 分布的随机浮点数。Beta 分布是在区间 [0,1] 上定义的一系列连续概率分布。它取决于两个正参数 alpha (α) 和 beta (β) 的值,这两个参数都必须大于 0。
此 Beta 分布广泛用于对约束在有限区间内的随机变量进行建模,使其成为表示各个字段中的百分比和比例的理想选择。
语法
以下是 betavariate() 方法的语法 -
random.betavariate(alpha, beta)
参数
此方法接受以下参数 -
- alpha:这是 Beta 分布的第一个 shape 参数。
- beta:这是 Beta 分布的第二个 shape 参数。
返回值
此方法返回一个遵循 beta 变量分布的随机浮点数。此数字将始终在 [0,1] 范围内(包括 [0,1])。
示例 1
让我们看一个使用 random.betavariate() 方法生成单个随机浮点数的基本示例。
import random
# Alpha and beta for the Beta distribution
alpha = 2
beta = 3
# Generate a random number from the Beta distribution
random_value = random.betavariate(alpha, beta)
print("Random value from Beta distribution:", random_value)
以下是输出 -
Random value from Beta distribution: 0.6127913057402181
注意:由于程序的随机性,每次运行程序时生成的 Output 都会有所不同。
示例 2
此示例使用 random.betavariate() 方法生成随机浮点数列表。
import random
# Alpha and beta for the Beta distribution
alpha = 2
beta = 5
# Generate a sample of 10 random numbers from the Beta distribution
random.seed(100)
sample = [random.betavariate(alpha, beta) for _ in range(10)]
print("List of random numbers from Beta distribution:", sample)
在执行上述代码时,您将获得如下所示的类似输出 -
List of random numbers from Beta distribution: [0.08771503465642065, 0.3103605168954117, 0.20939661454390773, 0.2837877667783816, 0.1266513481787254, 0.14773097492841658, 0.2744865269236881, 0.15785506249274603, 0.2810919299409675, 0.5240571971266883]
示例 3
这是另一个使用 random.betavariate() 方法从 beta 变量分布中生成 1000 个随机浮点数的列表的示例。然后,它会计算并打印这些数字的平均值。
import random
# Define alpha and beta for the Beta distribution
alpha = 3
beta = 1
# Generate a sample of 1000 random numbers from the Beta distribution
random.seed(100)
sample = [random.betavariate(alpha, beta) for _ in range(1000)]
# Display the average
print("Average of the sample: ",round(sum(sample) / len(sample), 2))
上述代码的输出如下 -
Average of the sample: 0.75