2

I am rewriting (and parallelising) some Stata simulations in C++.

For testing purposes I would like to use Stata's random numbers.

So far my approach has been to generate the numbers in Stata, dump them to a CSV file (100s MB), and then read that in my C++ program. This is slow and inelegant.

Ideally I would like to generate the same uniforms with C++ code.

I have read that Stata uses the KISS algorithm (cite http://blog.stata.com/tag/random-numbers/). I found a C implementation at http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf . But there are several variations of KISS, and there seems still a little work to make this take a single Stata style seed, and produce uniform numbers (the Stata blog suggests we take the binary expansion of the 32 bit int produced and return 0.binary_expansion).

Has anyone already written C/C++ code that will replicate numbers returned from Stata's uniform()?

Edit: the KISS seed computed using Stata's "set seed" seem to depend on an secret function. Cite = http://hsphsun3.harvard.edu/cgi-bin/lwgate/STATALIST/archives/statalist.1210/date/article-1132.html

P.Windridge
  • 246
  • 2
  • 11

1 Answers1

1

I eventually discovered it is possible to call C/C++ code from within Stata, by means of a plugin.

In particular it is possible to use C++11's Mersenne Twister RNG from within Stata.

Code (cpprandom.cpp) and a demonstration (cpprandom.do) is on my github account. You need the files stplugin.c and stplugin.h from the Stata plugin website (and a modern C++ compiler, of course).

P.Windridge
  • 246
  • 2
  • 11
  • Helpful details. Note that random number generation is much revised within Stata 14, released 7 April 2015. http://www.stata.com/stata14/random-number-generators/ – Nick Cox Apr 13 '15 at 17:22
  • Oh thanks, that looks a handy link. There are a few more details about how they set the seed in the KISS generator too. – P.Windridge Apr 14 '15 at 08:55