I am using Mersenne's 32-bit random number generator in C and was wondering how to use that number to generate on in some domain [a,b]. I know how it is done with rand(), dividing by RAND_MAX, but if I do the same thing and divide by the max of this generator, 2^(32)-1, it does not give me results between [a,b]. Is this not the proper value to use?
As a minimal working example:
#include<stdio.h>
#include<limits.h>
#include<float.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
#include<inttypes.h>
#include "mtwist.h"
#include<stdint.h>
int main(int argc, char *argv[])
{
int i;
mt_state rng;
mts_seed32(&rng, time(0));
int MT_MAX=(int) pow(2,32)-1;
double r;
for(i=0; i<10; i++)
{
r= -1 + 2*( (double) mts_lrand(&rng)/ MT_MAX);
printf("%.04f\n",r);
}
return 0;
}
gives the output:
-0.1171
-0.8587
0.3018
-0.7313
1.9769
0.9285
0.2120
2.9421
2.5656
-0.8976
when used with rand() and RAND_MAX gives a pseudo random number in the range [-1,1], but does not when I run this.
Aucun commentaire:
Enregistrer un commentaire