Skip to content

C library to use the standalone Rmath library with the Mersenne Twister random number generator

License

Notifications You must be signed in to change notification settings

mclements/rmath_mt

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rmath_mt: C library to use the standalone Rmath library with the Mersenne Twister random number generator

Summary

The standalone Rmath library provides a built-in Marsaglia-multicarry uniform random number generator and a number of non-uniform random number functions. This small C library demonstrates using the Rmath library with a Mersenne Twister (MT) random number generator and with initial values as per R.

The r_set_seed(unsigned int) function can be called to set the initial values for the MT generator, where the argument is as per the set.seed(n) function in R.

Linking requires over-writing the functions void set_seed(unsigned int, unsigned int) (ignoring the second argument), double unif_rand(void) and double R_unif_index(double), which are defined in Rmath.h. This requires using the static library libRmath.a rather than a shared library (e.g. libRmath.so).

Test

The file test.c is:

#include "Rmath_mt.h"

void printLn(double x) {
  printf("%f\n", x);
}

int main() {
  printLn(unif_rand());
  r_set_seed(1234);
  printLn(unif_rand());
  printLn(runif(0.0, 1.0));
  printLn(pnorm(1.96, 0, 1, 1, 0));
  printLn(dwilcox(100, 10, 20, 0));
  printLn(pwilcox(100, 10, 20, 0, 0));
  printLn(qwilcox(0.5, 10, 20, 0, 0));
  printLn(rwilcox(10, 20));
  return 0;
}

We can compile and run this using:

gcc --static -o test test.c Rmath_mt.c -lRmath -lm
./test
0.113703
0.113703
0.622299
0.975002
0.017240
0.491380
100.000000
111.000000

This shows that the default seed is 1234, whereas in R the default seed is random. We can run equivalent code in R:

set.seed(1234)
print(runif(1))
set.seed(1234)
print(runif(2))
print(pnorm(1.96))
print(dwilcox(100,10,20))
print(pwilcox(100,10,20,0))
print(qwilcox(0.5,10,20))
print(rwilcox(1,10,20))
[1] 0.1137034
[1] 0.1137034 0.6222994
[1] 0.9750021
[1] 0.01723983
[1] 0.4913801
[1] 100
[1] 111

About

C library to use the standalone Rmath library with the Mersenne Twister random number generator

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published