uniform() 和 triangular() 有什么区别?

What is the difference between uniform() and triangular()?

据我所知,random 模块有一组方法,其中包括 uniform() 和 triangular() return 两个给定参数之间的随机浮点数。它们之间没有区别吗?是否有任何特定情况我们应该使用一个而不是另一个?

文档

Documentation是你的朋友

random.uniform(a, b) Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().

random.triangular(low, high, mode) Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution


差异

所以 random.triangular 建模 triangular distribution which has strong similarities to a uniform distribution

这些方法的主要区别在于 random.triangularmode 参数,它提供了更细粒度的分布控制。

对于常规 Uni(a,b) 分布,您可能应该使用 random.uniform。根据 Wiki,即使模式设置为 0,三角分布 也不同于 均匀分布

This distribution for a = 0, b = 1 and c = 0 is the distribution of X = |X1 − X2|, where X1, X2 are two independent random variables with standard uniform distribution.

所以 random.triangular 应该精确地用于使用三角分布。


例子

这是一个简单的例子,强调了两种方法的differences/similarities

import random


# Set Seed for reproducibility
random.seed(123)

# Parameters
lo: int = 0
hi: int = 100
mode: int = 10
sample_size: int = int(1e+6)

# Samples
uni = (random.uniform(lo, hi) for _ in range(sample_size))
tri1 = (random.triangular(lo, hi, mode) for _ in range(sample_size))
tri2 = (random.triangular(lo, hi) for _ in range(sample_size))


# Printing averages
print(round(sum(uni) / sample_size, 2))
# 50.01
print(round(sum(tri1) / sample_size, 2))
# 36.68
print(round(sum(tri2) / sample_size, 2))
# 50.0