Truncated normal with a given mean

吃可爱长大的小学妹 提交于 2019-12-11 04:09:13

问题


Is it possible in python to generate a truncated normal distribution with a given expected value? I know that scipy.stats.truncnorm can give a truncated normal distribution that takes the mean of the original normal distribution as a parameter, but I want to create a truncated normal distribution such that the expected value of the truncated distribution is a particular value. Is this possible?


回答1:


You could convert between mu and mean, see https://en.wikipedia.org/wiki/Truncated_normal_distribution for details, for mean there is simple expression, to get mu you have to solve nonlinear equation

import scipy
from scipy.stats import norm

def get_mean(mu, sigma, a, b):
    alpha = (a - mu)/sigma
    beta  = (b - mu)/sigma
    Z     = norm.cdf(beta) - norm.cdf(alpha)
    return mu + (norm.pdf(alpha) - norm.pdf(beta)) / Z

def f(x, mean, sigma, a, b):
    return mean - get_mean(x, sigma, a, b)

def get_mu(mean, sigma, a, b):
    mu = scipy.optimize.brentq(f, a, b, args=(mean, sigma, a, b))
    return mu

a  = -2.0
b  = 3.0
sigma = 1.0
mu    = 0.0

mean = get_mean(mu, sigma, a, b)
print(mean)

mu = get_mu(mean, sigma, a, b)
print(mu)

After getting mu from desired mean, you could put it into sampling routine



来源:https://stackoverflow.com/questions/49535223/truncated-normal-with-a-given-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!