[R] generate random numeric
Ken Peng
ken @end|ng |rom pubbox@net
Sat Oct 30 02:08:44 CEST 2021
That's all right. Thanks.
On Sat, Oct 30, 2021 at 12:29 AM Marc Schwartz <marc_schwartz using me.com> wrote:
> Ken Peng wrote on 10/29/21 2:39 AM:
> > I saw runif(1) can generate a random num, is this the true random?
> >
> >> runif(1)
> > [1] 0.8945383
> >
> > What's the other better method?
> >
> > Thank you.
> >
> Hi,
>
> You do not indicate your use case, and that can be important.
>
> The numbers generated by R's default RNGs are "pseudo random" (PRNGs),
> which means that for most general purpose applications, such as common
> Monte Carlo simulations or randomized clinical trial treatment
> allocations, as suggested by the other replies, they will work fine.
>
> As PRNGs, the actual pseudo-random permutations can be replicated by
> setting the same 'seed' value each cycle for the PRNG in use.
>
> For example:
>
> > runif(5)
> [1] 0.6238892 0.8307422 0.4955693 0.4182567 0.9818217
>
> > runif(5)
> [1] 0.2423170 0.4129066 0.9213000 0.8290358 0.1644403
>
> will yield two different, pseudo-random, sequences.
>
> However:
>
> > set.seed(1)
> > runif(5)
> [1] 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819
>
> > set.seed(1)
> > runif(5)
> [1] 0.2655087 0.3721239 0.5728534 0.9082078 0.2016819
>
> will yield the same sequence given the use of the same seed value before
> each call to runif().
>
> Thus, the sequences will appear to be random, but given a specific
> algorithm and seed value, they are deterministic.
>
> That repeatable behavior can be important if one wishes to come back at
> some future date and replicate the exact same output sequence, presuming
> other factors have not changed in the mean time, such as occurred with R
> version 3.6.0, which is referenced in ?Random, where a default changed
> to improve behavior.
>
> Also, some R functions may use simulation or resampling approaches to
> create various parameters, and you may wish to replicate the same result
> with each iteration. Setting the seed value prior to the relevant
> function call can enable that.
>
> Also, review the resources at https://www.random.org for additional
> references on the differences between PRNGs and other implementations,
> especially if you might need something closer to a "true" RNG for more
> rigorous work.
>
> Regards,
>
> Marc Schwartz
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list