[R] random sequences for rnorm and runif

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Feb 3 14:39:02 CET 2011


On Thu, 3 Feb 2011, Matthias Gondan wrote:

> Dear R experts,
>
> For a fixed seed, the first random number produced by rnorm and runif
> has the same rank within the distribution, which I find useful. The
> following ranks differ, however.
>
>> set.seed(123)
>> runif(4)
> [1] *0.2875775* 0.7883051 *0.4089769* 0.8830174
>
>> set.seed(123)
>> pnorm(rnorm(4))
> [1] 0.2875775 0.4089769 0.9404673 0.5281055
>
> I noticed that rnorm seems to 'eat' two seeds of the random
> number generator, whereas runif eats only one seed. Is this
> intended behavior or do you think it should be fixed?

Yes, it is the intended and documented procedure.  To achieve 
sufficient accuracy by the default inversion method for rnorm, 2 
uniforms are required.

> The strange thing is that the 1st/3rd/5th etc number of rnorm
> corresponds to the 1st/2nd/3rd in runif.

It would be strange if true: look again and interchange
rnorm <-> runif.

> If two seeds are necessary, I would have expected the following 
> correspondence, 2-1, 4-2, 6-3, etc.
>
> Temporary fix:
>
>> myrnorm = function(n, mean=0, sd=1)
> + {
> +     qnorm(runif(n), mean, sd)
> + } # myrnorm

which for some purposes is not accurate enough.

>> set.seed(123)
>> pnorm(myrnorm(4))
> [1] 0.2875775 0.7883051 0.4089769 0.8830174

Better to simple take every other value in runif.

> Best wishes,
>
> Matthias Gondan
> -- 
> GMX DSL Doppel-Flat ab 19,99 Euro/mtl.! Jetzt mit
> gratis Handy-Flat! http://portal.gmx.net/de/go/dsl
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list