Re: a random number obeying Gaussian + within a range



Here is a function generating truncated Gaussin with correct standard deviation:

% Save this in TruncatedGaussian.m file (included 2 nested function)

function x = TruncatedGaussian(sigma, range, n)
% x = TruncatedGaussian(sigma, range, n)
% Generate a random vector of length n; truncated Gaussian Distribution X
% in [-range,range]; mean(X) = 0 and std(X)=sigma

% Search for "sigmac" such that the truncated Gaussian having sigmac in
% the formula in the pdf procides a standard deviation equal to sigma
[sigmac res flag] = fzero(@scz,1.5*sigma,[],sigma,range);

if flag<0 % Someting is wrong
fprintf('warning=range and sigma incompatible\n');
sigmac = sigma;
else
fprintf('sigmac=%g\n',sigmac)
sigtarget=stdtrunc(range, sigmac);
fprintf('sigma=%g\n',sigtarget)
end

% Inverse pg the cdf
c=1/(sqrt(2)*sigmac);
cdfinv = @(y) erfinv(y*2*erf(c*range) + erf(-c*range))/(c);
% Generate random
x=cdfinv(rand(1,n));

end

function stdt=stdtrunc(upper, sigma)
% Compute the standard deviation of a trunctated gaussian distribution
aa=upper./sigma;
it=erf(aa/sqrt(2));
corr=erf(aa/sqrt(2))-(2*aa)/sqrt(2*pi).*exp(-aa.^2/2);
stdt = sigma.*sqrt(corr./it);
end

function res=scz(sc, sigma, upper)
% Gateway for fzero
res = stdtrunc(upper, sc) - sigma;
end

% End of TruncatedGaussian.m

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Test this on command line:

sigma=2;
range=4;

x=TruncatedGaussian(sigma, range, 1e5);

mean(x)
std(x)
hist(x,64)

% Bruno
.



Relevant Pages

  • Re: a random number obeying Gaussian + within a range
    ... % Generate a random vector of size n; truncated Gaussian Distribution X ... % Search for "sigmac" such that the truncated Gaussian having sigmac in ... % the formula in the pdf procides a standard deviation equal to sigma ...
    (comp.soft-sys.matlab)
  • Re: Is there a possibility to have more than one ZERO vector in a space!?
    ... The metric space (S, sigma). ... sigma is the standard deviation of the observations. ... Form a right triangle from the first two observations from s1. ... To the end of the sum, add the third vector in the ...
    (sci.math)
  • Re: Gaussian Noise Generation
    ... subtracting the mean and dividing by the standard deviation. ... is your collection of random samples and each sample has mean M and ... sigma * sqrt ... you can use a linear filter (i.e. a boxcar ...
    (comp.dsp)
  • Re: An unbiased estimator of mu^2
    ... > a BIASED estimator of the population standard deviation ... s-squared is the unbiased estimate of the ... > the population standard deviation sigma? ...
    (sci.stat.math)
  • Chi square test help needed
    ... Now, in case of Poisson distribution, what is this sigma? ... standard deviation or the error the measurement error. ... is the sigma = standard deviation on observed data / sqrtin ...
    (sci.stat.math)

Loading