Open In App

numpy.random.geometric() in Python

Last Updated : 27 Sep, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Python
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.

Python
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

randomGeometricEx1

Explanation: histogram shows how the probability decreases as the number of trials increases for success probability 0.65.

Example 2: Here we use p = 0.85 with 1000 samples and visualize the distribution using 10 bins.

Python
import numpy as np
import matplotlib.pyplot as plt

arr = np.random.geometric(0.85, 1000)
plt.hist(arr, bins=10, density=True)
plt.show()

Output

randomGeometricEx2

Explanation: Since p = 0.85 is high, most successes occur within the first 1–2 trials, so the histogram is skewed towards smaller numbers.

Example 3: In this example, we generate a 2D array (3x3) of random values with p = 0.3.

Python
import numpy as np
arr = np.random.geometric(0.3, (3, 3))
print("2D array:")
print(arr)

Output
2D array:
[[ 1  1  3]
 [ 1 11 19]
 [ 4  2  4]]

Explanation: A 3x3 matrix is created, where each element is sampled from a geometric distribution with probability 0.3.


Explore