# st: a tip on random integers

 From "Nick Cox" To Subject st: a tip on random integers Date Wed, 14 Mar 2007 23:56:04 -0000

A small detail arose in a recent posting
of Svend Juul's that comes up frequently
elsewhere, so that a brief comment seems worthwhile.

Svend wanted to fake a dataset including
a month variable running over 1..12 so
he coded

. gen month = int(1 + 12 * uniform())

This is fine and works, as would

. gen month = 1 + int(12 * uniform())

but there is a neater way to do it:

. gen month = ceil(12 * uniform())

The story is that -uniform()- emits random
numbers between 0 and 1, but we often want random integers
over a different range, usually 1 up, so we must multiply
_and_ round to integers.

Many people have come across an integer function
in other software long since, so they have wired
in their memories the idea of using -int()-, which
was the first rounding function in Stata. But as -int()-
rounds down, you need to correct that by adding 1
whenever the desired range starts at 1.

However, -ceil()-, short for ceiling, rounds up
and gets you there directly.

There is another illustration of this in Bill Gould's
latest Mata column in the Stata Journal.

This is already a Stata Journal Tip on -ceil()- and
-floor()-:

SJ-3-4  dm0002  . . . . . . . . Stata tip 2: Building with floors and ceilings
Q4/03   SJ 3(4):446--447                                 (no commands)
tips for using floor() and ceil()

although not with this example.

Nick
n.j.cox@durham.ac.uk

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/