help-gsl
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

## [Help-gsl] accessing random number generator from functions

 From: Nathan Moore Subject: [Help-gsl] accessing random number generator from functions Date: Mon, 22 Nov 2004 21:45:28 -0600

This is a general question about the scope of random number generators. If I declare and initialize a random number generator (named "dice") within the main function, how can I get numbers from "dice" if I'm in a sub-function? Do I need to pass "dice" somehow?
```
Specific example follows.  Would appreciate any constructive comments.

regards,

Nathan Moore
University of Minnesota

eg, if I have the main function,

- - - - -
#define RANDOM_SEED 53

int main (void)
{
/* allocate an instance of the random number generator */
gsl_rng * dice = gsl_rng_alloc (gsl_rng_mt19937);

/* seed the generator */
gsl_rng_set( dice, (long)RANDOM_SEED );

/* generate a few doubles with the generator */
int i,i_limit=1000000;
double ave_x=0.0;
for(i=0;i<i_limit;i++) {
x = gsl_rng_uniform(dice);
ave_x+=x;
}
```
printf("average over %ld numbers was %lf\n",i_limit,ave_x/(double)i_limit);
```
/* free up memory that the generator uses */
gsl_rng_free (dice);

return 0;
}
- - - - -

```
How should the following code be phrased to use dice, but calculate the average within a function? (the code below DOESN'T work)
```
- - - -

#define RANDOM_SEED 53

double calculate_average( long num_terms);
double calculate_average( long num_terms)
{
int i;
double ave_x=0.0;
for( i=0; i<num_terms; i++) {
x = gsl_rng_uniform(dice);
ave_x += x;
}
return ave_x/(double)num_terms;
}

int main (void)
{
/* allocate an instance of the random number generator */
gsl_rng * dice = gsl_rng_alloc (gsl_rng_mt19937);

/* seed the generator */
gsl_rng_set( dice, (long)RANDOM_SEED );

/* generate a few doubles with the generator */
double ave_x;
long num_terms=1000000;
ave_x = calculate_average(num_terms);
printf("average over %ld numbers was %lf\n",num_terms,ave_x);

/* free up memory that the generator uses */
gsl_rng_free (dice);

return 0;
}

```

reply via email to

 [Prev in Thread] Current Thread [Next in Thread]