The Geometric distribution tells us how many trials it takes to get the first success when each trial has same probability of success p. In Python, numpy.random.geometric() generates random numbers following this distribution. Each number represents the count of attempts needed until the first success.
In this simple example, we generate a single random value from a geometric distribution with success probability p = 0.5.
import numpy as np
x = np.random.geometric(p=0.5)
print(x)
Output
3
Explanation: Here, result 3 means it took 3 trials to get the first success, given each trial has a 50% chance of success.
Syntax
numpy.random.geometric(p, size=None)
Parameters:
- p (float): Probability of success (0 < p ≤ 1).
- size (int or tuple, optional): Output shape. If None, returns a single value.
Returns: out (ndarray or int) Random samples from a geometric distribution.
Examples
Example 1: This code generates 1000 random values with p = 0.65 and plots their histogram.
import numpy as np
import matplotlib.pyplot as plt
arr = np.random.geometric(0.65, 1000)
plt.hist(arr, bins=40, density=True)
plt.show()
Output