I am trying to sample numbers from truncated normal distribution given particular variance and bounds of the resulting numbers, e.g. I need numbers with mean 0 and unit variance, but they must be within some bounds, for example [-2, 2]
I can't figure out how to truncate the distribution while keeping the variance.
import math
import numpy as np
import scipy.stats as stats
truncation = 2
lower, upper = -truncation, truncation
mu, sigma = 0, 1
num_samples = 1000
if truncation:
n = stats.truncnorm((lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)
samples = n.rvs(num_samples)
std_trunc = np.std(samples)
n = stats.norm(loc=mu, scale=sigma)
samples = n.rvs(num_samples)
std_simple = np.std(samples)
print(std_trunc, std_simple, sep='\n')
# outputs
# 0.859167285015 # I need number close to 1 here
# 1.01735583631 # like here, but here it's not truncated
Aucun commentaire:
Enregistrer un commentaire