Reputation: 5212
I am newbie to numpy and recently I got very confused on the random.normal method I would like to generate a 2 by 2 matrix where the mean is zero so I wrote the following, however, as you can see the abs(0 - np.mean(b)) < 0.01 line outputs False, why? I expect it to output True.
>>> import numpy as np
>>> b = np.random.normal(0.0, 1.0, (2,2))
>>> b
array([[-1.44446094, -0.3655891 ],
[-1.15680584, -0.56890335]])
>>> abs(0 - np.mean(b)) < 0.01
False
Upvotes: 0
Views: 862
Reputation: 14399
If you want a generator, you'll need to manually fix the mean and std to your expected values:
def normal_gen(m, s, shape=(2,2)):
b = np.random.normal(0, s, shape)
b = (b - np.mean(b)) * (s / np.std(b)) + m
return b
Upvotes: 1
Reputation: 473
Sampling from a normal distribution does not guarantee that the mean of your sample is the same as the mean of the normal distribution. If you take an infinite number of samples, it should have the same mean (via the Central Limit Theorem) but obviously, you can't really take an infinite number of samples.
Upvotes: 0