Shortcut for chapter specific information

Monday, June 20, 2011

Generating random numbers


To test several routines I wrote including sorting and the recent maximum subarray procedure.  I decide to write a simple random number generator.  
This is rather trivial provided that you got the calculation right.  In a typical implementation such as GNU. RAND_MAX is usually the INT_MAX so you also need to make sure there is no overflow.  It doesn't make this task difficult at all.  A version I wrote can be found here

#include <stdio.h>
#include <stdlib.h>
#define N 100

int main(int c, char* v[])
{
  int A[N];
  int i;
  for(i=0;i<N;i++){
    A[i]= 1 + (int ) (N * (float)rand()/(float)RAND_MAX);
    printf("%d ", A[i]);
  }
  printf("\n");
}

No comments:

Post a Comment