Skip to content
Prev 176211 / 398503 Next

Code of sample() in C

Thanks, Ranjan! I have tried to use the function SampleNoReplace in
random.c, which seems to work, except that I get always the same
random numbers (with your code the same happens). (My code is below.).

I have read the documentation ("Writing R extensions"), where it is advised:

?The interface to R?s internal random number generation routines is

double unif_rand();
double norm_rand();
double exp_rand();

giving one uniform, normal or exponential pseudo-random variate.
However, before these are used, the user must call

GetRNGstate();

and after all the required variates have been generated, call

PutRNGstate();?

However, when I use GetRNGstate() and PutRNGstate(), I get the following errors:

$ gcc -I/usr/include/R -o myprog myprog.c -lRmath -lm
/tmp/cc6CMnlh.o: In function `main':
myprog.c:(.text+0x30): undefined reference to `GetRNGstate'
myprog.c:(.text+0x57): undefined reference to `PutRNGstate'
collect2: ld returned 1 exit status
$

Any ideas?

Paul

--------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <R.h>
#include <Rmath.h>
#define MATHLIB STANDALONE
#include <math.h>

void snr(int k, int n, int *y, int *x);

int main()
{

  int *x = malloc(50*sizeof(int));
  int *y = malloc(5*sizeof(int));
  int i;

  GetRNGstate();
  snr(5,50,y,x);
  PutRNGstate();

  for(i=0;i<5;++i)
    printf("%d ",y[i]);

  free(x);
  free(y);

  return 0;

}


void snr(int k, int n, int *y, int *x)
{
    int i, j;
    for (i = 0; i < n; i++)
        x[i] = i;
    for (i = 0; i < k; i++) {
        j = n * unif_rand();
        y[i] = x[j] + 1;
        x[j] = x[--n];
    }
}

--------------------------------------
On Sun, Apr 5, 2009 at 11:00 PM, Ranjan Maitra <maitra at iastate.edu> wrote: