students
students

Reputation: 51

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

As far as i've understood, the random module has a set of methods, among which both uniform() and triangular() return a random float number between two given parameters. Is there no difference between them? Is there any specific case in which we should use one over the other?

Upvotes: 0

Views: 953

Answers (1)

niko
niko

Reputation: 5281

Documentation

Documentation is your friend

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


Difference

So random.triangular models a triangular distribution which has strong similarities to a uniform distribution.

The main difference in the usage of the methods is the mode argument of random.triangular which provides more a granular level of control over the distribution.

For a regular Uni(a,b) distribution, you should probably use random.uniform. According to Wiki, even when the mode is set to 0, a triangular distribution is not the same as a uniform distribution

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.

So random.triangular should be used precisely for using triangular distributions.


Example

Here is a simple example highlighting the differences/similarities of both methods

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

Upvotes: 1

Related Questions