# [R] how to generate a normal distribution with mean=1, min=0.2, max=0.8

Mike Miller mbmiller+l at gmail.com
Fri Apr 29 02:24:41 CEST 2011

```Good point.  It would be absurdly inefficient if the upper and lower
limits on the interval of interest were, say, 0.2 and 0.201 instead of 0.2
and 0.8.  Here's what I think is probably the best general approach:

Compute the CDF for the upper and lower limits of the interval and
generate uniform random numbers within that range of CDF values, then
compute the inverse CDF of those values.  To be explicit:

n <- 1000
L <- .2
U <- .8

p_L <- pnorm(L)
p_U <- pnorm(U)

x <- qnorm(runif(n, p_L, p_U))

It is very fast and it always produces exactly the desired number ("n") of
random normal values.

Mike

--
Michael B. Miller, Ph.D.
Bioinformatics Specialist
Minnesota Center for Twin and Family Research
Department of Psychology
University of Minnesota

On Thu, 28 Apr 2011, Carl Witthoft wrote:

> That method (creating lots of samples and throwing most of them away) is
> usually frowned upon :-).
>
> Try this:  (I haven't, so it may well have syntax errors)
>
> % n28<- dnorm(seq(.2,.8,by=.001),mean=1,sd=1)
>
> % x <- sample(seq(.2,.8,by=.001), size=500,replace=TRUE, prob=n28)
>
> And I guess in retrospect this  will get really ugly if you want, say, a
> sampling grid resolution of 1e-6 or so.
>
> Anyone know what's applicable from the "sampling" package?
>
>
> Carl
>
> -------<quote>__________________
> From: David Winsemius <dwinsemius_at_comcast.net>
> Date: Thu, 28 Apr 2011 13:06:21 -0400
>
> On Apr 28, 2011, at 12:09 PM, Ravi Varadhan wrote:
>
>> Surely you must be joking, Mr. Jianfeng.
>>
>
> Perhaps not joking and perhaps not with correct statistical specification.
>
> A truncated Normal could be simulated with:
>
> set.seed(567)
> x <- rnorm(n=50000, m=1, sd=1)
> xtrunc <- x[x>=0.2 & x <=0.8]
> require(logspline)
> plot(logspline(xtrunc, lbound=0.2, ubound=0.8, nknots=7))
>
> --
> David.
>
>
>
>
>> -----Original Message-----
>
>> From: r-help-bounces_at_r-project.org
> [mailto:r-help-bounces_at_r-project.org
>
>> ] On Behalf Of Mao Jianfeng
>
>
>
>> Dear all,
>
>>
>
>> This is a simple probability problem. I want to know, How to
>
>> generate a
>
>> normal distribution with mean=1, min=0.2 and max=0.8?
>
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help