Obtain a random number from a truncated normal distribution

61 次查看(过去 30 天)
Hello everyone,
I want to obtain a random number from a truncated normalized distribution. Let's say that we have the following:
magnetization=0.9;
upper_limit=magnetization+magnetization*0.03;
lower_limit=magnetization-magnetization*0.03;
Now, imagine that we want to obtain the aforementioned random number from a truncated normalized distribution such that its mean value will be equal to magnetization, and its standard deviation will be given by, for example, sigma=1. I have seen that I can create my distribution easily from https://es.mathworks.com/help/stats/prob.normaldistribution.truncate.html. But how can I extract from here a random number [magnetization-0.03*magnetization, magnetization+0.03*magnetization] according to this distribution in which not all numbers are equally probable?
I have seen also that there exist this function: https://es.mathworks.com/matlabcentral/fileexchange/53180-truncated-normal-generator, but I am not sure how it works.
Any idea?

采纳的回答

Jeff Miller
Jeff Miller 2020-10-19
You seem to be asking for something like this:
pretruncMean = 0.9;
pretruncSD = 1;
untruncated = makedist('Normal',pretruncMean,pretruncSD);
truncated = truncate(untruncated,pretruncMean-0.03,pretruncMean+0.03);
r = random(truncated,100000,1);
mean(r)
std(r)
histogram(r)
But note that the random numbers are almost uniformly distributed. This is because the untruncated normal is pretty flat in the narrow region where you are truncating. If you reduce the pretruncSD to (say) 0.03, the generated random numbers will look much more like a normal with the tails chopped off.

更多回答(2 个)

saeid darvishi
saeid darvishi 2021-1-8
pretruncMean = 0.9;
pretruncSD = 1;
untruncated = makedist('Normal',pretruncMean,pretruncSD);
truncated = truncate(untruncated,pretruncMean-0.03,pretruncMean+0.03);
r = random(truncated,100000,1);
mean(r)
std(r)
histogram(r)

Bruno Luong
Bruno Luong 2021-1-8
编辑:Bruno Luong 2021-1-8
In theory if you range is something +/-0.9*0.03 the maximum possible standard deviation you can reach with a truncated gaussian distribution is
>> 2*0.9*0.03/sqrt(12)
ans =
0.0156
You won't ever able to generate distribution with sigma larger than this limit, such as 1 (or even 0.03).
If you provide more reasonable value, you can use my tool here
desired_std = 0.01 % < 0.0156
r = 0.9+TruncatedGaussian(desired_std,[-1 1]*0.9*0.03,[1 1e6]);
histogram(r)
std(r) % Check
returns as expected
ans =
0.0100

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by