知識社群Login
10秒鐘,可以產生 六千萬個 亂數
by 高顯忠, 2010-12-14 12:21, Views(1852)
#include "inc-01.h"
// ----------------------------------------------

//   rnd1(    &s1);
void rnd1(int *s1)
{
double x1, x2;
x1= (double) (*s1);
// x1= (x1*a + b) mod c;// a= 16807, b= 0, c= 2147483647
x2= fmod((x1*16807.0), 2147483647.0);
(*s1)= (int) (x2 + 0.5);
}// end of rnd1()
// ----------------------------------------------

//   init_rnd(    &s1);
void init_rnd(int *s1)
{
int t1, t2, i;
time1(&t1);// get t1
t2= t1;// t2 == t1
while (t2 == t1) {
time1(&t1);// get a new t1
}
// t1 <> t2
for (i=0;i<300;i++) {
rnd1(&t1);
}
(*s1)= t1;
}// end of init_rnd()
// ----------------------------------------------

//   swap_int(&i1, &i2);
void swap_int(int *i1, int *i2)
{
int temp;
temp= *i1;
*i1= *i2;
*i2= temp;
}// end of swap_int()
// ----------------------------------------------

//   rnd2(s1, &x);
void rnd2(int *s1, double *x)
{
rnd1(s1);
*x= ((double) *s1)/2147483648.0;
}// end of rnd2()
// ----------------------------------------------

//   irnd(&s1, i1, i2, &ii);
void irnd(int *s1, int i1, int i2, int *ii)
{
// must i1 <= i2
if (i1 > i2) {
swap_int(&i1, &i2);
}
double x;
rnd2(s1, &x);
(*ii)= (int) (x*(i2 - i1 + 1) + i1);
}// end of 
// ----------------------------------------------

int main()
{
int s1, t1, i, no;
double dt;
no= (int) (6000e4 + 0.5);
init_rnd(&s1);
time1(&t1);
for (i=0;i<no;i++) {
rnd1(&s1);
}
time2(t1, &dt);
printf("no= %ld, dt= %.3lf\n", no, dt);
pause();
return(0);
}
// ----------------------------------------------

#if 0

no= 60000000, dt= 10.125
Press [Esc] for stop! other key for continue...

#endif
// ----------------------------------------------