Stata random number generator in C(++)
Asked Answered
W

1

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

Wept answered 2/4, 2015 at 17:41 Comment(2)
Paging @NickCox : any ideas?Wept
Sorry, no. You want to replicate proprietary code that is not visible to the user and so I can't comment.Vaientina
W
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).

Wept answered 13/4, 2015 at 15:32 Comment(2)
Helpful details. Note that random number generation is much revised within Stata 14, released 7 April 2015. stata.com/stata14/random-number-generatorsVaientina
Oh thanks, that looks a handy link. There are a few more details about how they set the seed in the KISS generator too.Wept

© 2022 - 2024 — McMap. All rights reserved.