产生随机数 满足指数分布的[M,N]区间随机数,其中 M,N 是正整数。
产生随机数 满足指数分布的[M,N]区间随机数,其中M,N是正整数。解题思路
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { double lambda = 3.5; const int nrolls = 10000; // number of experiments const int nstars = 100; // maximum number of stars to distribute #define nintervals 10 // number of intervals int p[nintervals] = { 0 }; for( int i=0; i<nrolls; ++i ) { double number = (-log(1 - rand()/(RAND_MAX+1.0)) / lambda); if (number<1.0) ++p[(int)(nintervals*number)]; } for( int i=0; i<nintervals; ++i ) { printf( "%.1f-%.1f: ", (float)(i)/nintervals, (float)(i+1)/nintervals ); for( int j=0; j!=p[i]*nstars/nrolls; ++j ) putchar( '*' ); putchar( '\n' ); } #undef nintervals return 0; }输出
0.0-0.1: ***************************** 0.1-0.2: ******************** 0.2-0.3: *************** 0.3-0.4: ********** 0.4-0.5: ******* 0.5-0.6: ***** 0.6-0.7: *** 0.7-0.8: ** 0.8-0.9: * 0.9-1.0: *