TAGS :Viewed: 2 - Published at: a few seconds ago

[ non-random sampling versions of np.random.normal ]

I'm trying to generate a single array that follows an exact gaussian distribution. np.random.normal sort of does this by randomly sampling from a gaussian, but how can I reproduce and exact gaussian given some mean and sigma. So the array would produce a histogram that follows an exact gaussian, not just an approximate gaussian as shown below.

mu, sigma = 10, 1
s = np.random.normal(mu, sigma, 1000)

fig = figure()
ax = plt.axes()

totaln, bbins, patches = ax.hist(s, 10, normed = 1, histtype = 'stepfilled', linewidth = 1.2)

plt.show()

Answer 1


If you'd like an exact gaussian histogram, don't generate points. You can never get an "exact" gaussian distribution from observed points, simply because you can't have a fraction of a point within a histogram bin.

Instead, plot the curve in the form of a bar graph.

import numpy as np
import matplotlib.pyplot as plt

def gaussian(x, mean, std):
    scale = 1.0 / (std * np.sqrt(2 * np.pi))
    return scale * np.exp(-(x - mean)**2 / (2 * std**2))

mean, std = 2.0, 5.0
nbins = 30
npoints = 1000

x = np.linspace(mean - 3 * std, mean + 3 * std, nbins + 1)
centers = np.vstack([x[:-1], x[1:]]).mean(axis=0)
y = npoints * gaussian(centers, mean, std)

fig, ax = plt.subplots()
ax.bar(x[:-1], y, width=np.diff(x), color='lightblue')

# Optional...
ax.margins(0.05)
ax.set_ylim(bottom=0)

plt.show()

enter image description here