Stata/Random Number Generation

From Wikibooks, open books for an open world
< Stata
Jump to: navigation, search

Generate a univariate uniform distribution[edit]

  • The function -runiform()- returns uniformly distributed pseudorandom numbers on the interval [0,1)
. set obs 10
obs was 0, now 10
. gen x = runiform()

You have built-in random number generation methods for the main distributions. The keyword is rnd. The list of all available distributions is given in the following help file: -h rnd-

The Inverse CDF method[edit]

  • The basic function for generating random numbers is uniform(). Therefore you generally have to use the inverse CDF method to sample from other distributions.

We can draw from a uniform distribution :

. clear
. set obs 500
obs was 0, now 500
. gen unif=runiform()
. hist unif
(bin=22, start=.0043096, width=.04522361)

We can draw from a normal distribution :

. gen norm=invnorm(runiform())
. hist norm
(bin=22, start=-2.8517358, width=.23821211)

We can draw from a Failed to parse (MathML with SVG or PNG fallback (recommended for modern browsers and accessibility tools): Invalid response ("Math extension cannot connect to Restbase.") from server "/mathoid/local/v1/":): {\displaystyle \chi^2} distribution

. gen chi2=invchi2(1,uniform())
. hist chi2
(bin=22, start=.00002381, width=.50381869)
. gen chi210=invchi2(10,uniform())
. hist chi210
(bin=22, start=1.8273849, width=1.3336678)

We can draw from a Fisher Snedecor distribution

. gen fisher=invF(10,10,uniform())
. hist fisher
(bin=22, start=.14025442, width=.39209784)

We can draw from a Student distribution. Remember that invttail() is not the inverse of the CDF (cumulative distribution function) but the inverse of the survival function (1 - the CDF).

. gen student=1-invttail(10,uniform())
. hist student
(bin=22, start=-3.9568543, width=.4741968)

Multivariate Normal Distributions[edit]

drawnorm draws directly from a multivariate normal distribution.

Previous: Probability Function Index Next: Data Management