get a normally distributed random number in python

To generate a normally distributed random number in Python, we can use the random module from the Python standard library or the numpy library. The random module provides the gauss method to generate random numbers from the normal (Gaussian) distribution. The numpy library provides the normal method to generate random samples from the normal distribution.

Here is an example code snippet for both methods:

main.py
import random
import numpy as np

# using random module
mu = 0  # mean
sigma = 1  # standard deviation
num_samples = 10
samples = [random.gauss(mu, sigma) for _ in range(num_samples)]
print(samples)

# using numpy library
samples = np.random.normal(mu, sigma, num_samples)
print(samples)
288 chars
14 lines

In this code snippet, we first define the mean and standard deviation of the normal distribution (mu and sigma) and the number of samples (num_samples).

Then we use the gauss method from the random module to generate random samples using a for loop. Alternatively, we can use the numpy library and call the normal method with the specified distribution parameters and the number of samples.

Finally, we print the generated samples for both approaches.

gistlibby LogSnag