模擬丟骰子 兩億次,
花費時間 17.901秒
// for fast random number generator
#include "inc-01.h"
// ----------------------------------------------
// rnd2(&s1, &x);
void rnd2(int *s1, double *x)
{
rnd1(s1);
(*x)= ((double) *s1)/2147483647.0;
}// end of rnd2()
// ----------------------------------------------
// swap_int( &i1, &i2);
void swap_int(int *a, int *b)
{
int temp;
temp= *a;
*a= *b;
*b= temp;
}// end of swap_int()
// ----------------------------------------------
// 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)= i1 + ((int) ((i2 - i1 + 1)*x));
}// end of irnd()
// ----------------------------------------------
int main(int argc, char *argv[])
{
// for rnd1(), rnd2(), irnd(), ...
int t1, t2, s1, s2, no, min, max, i, i1, i2, ii;
int u[18]= {0};
double ct= 0.0, dt, x;
i1= 1;
i2= 6;
time1(&s1);// s1 是種子數
no= (int) (2E+8 + 0.5);
time1(&t1);
for (i=1;i<=no;i++) {
irnd(&s1, i1, i2, &ii);
u[ii+6]++;
}
time2(t1, &dt);
skip(3);
printf("dt= %.3lf \n", dt);
skip(3);
for (i=0;i<18;i++) {
if (u[i] > 0)
printf("i= %5d, u[i]= %10ld, %10.6lf \n",
i, u[i], (((double) u[i])/no));
}
pause();
return EXIT_SUCCESS;
}// end of main()
|