1.概率均匀分布(C语言)
#include <stdio.h> #include <stdlib.h> #include <time.h> int main( int argc, char **argv) { int i=0, v, mod, n; /* srand函数是随机数发生器的初始化函数 */ srand((unsigned) time(NULL));//此行可以删除 mod = 10;//range of random n = 100000;//number of random int *count = malloc(sizeof(int)*mod); i=0; do{ count[i++] = 0; }while(i<mod); i=0; do{ i++; v = rand() % mod; printf("%2d ", v); if(i%10 == 0) printf("\n"); count[v] ++; }while(i<n); i=0; do{ printf("count[%d] = %d\n",i, count[i]); i++; }while(i<mod); return 0; }
结果:
count[0] = 9973 count[1] = 10146 count[2] = 9909 count[3] = 9837 count[4] = 10079 count[5] = 10111 count[6] = 9999 count[7] = 10002 count[8] = 9977 count[9] = 9967
2.正太分布公式(C语言)
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifndef pi #define pi 3.141592653 #endif int main( int argc, char **argv) { int mu = 5, cigma = 1; int n, ix; float dn, x; n = 100; dn = 0.1; float *N = malloc(sizeof(float)*n); for(ix=0, x=0; ix<n; ix++, x+=dn) { printf("%d, %f\n",ix, x); N[ix] = sqrt(1.0/(2*pi*cigma*cigma))*exp( -1.0/(2.0*cigma*cigma)*(x - mu)*(x - mu) ); } FILE *fp = fopen("normal.txt","w"); for(ix = 0; ix < n; ix ++) fprintf(fp,"%f\n",N[ix]); fclose(fp); return 0; }
结果成图:
3.中心极限定理(大数定理)
该定理的定义为很多随机变量的和近似服从正太分布,给出代码并改变参数作图:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #ifndef pi #define pi 3.141592653 #endif float Normal_0(float mu, float cigma, float x) /* normal distribution with fmulation */ { return sqrt(1.0/(2*pi*cigma*cigma)) *exp( -1.0/(2.0*cigma*cigma)*(x - mu)*(x - mu) ); } #define NSUM 250 int Normal_1() /*Theorem of large numbers or Central Limit Theorem */ { srand((unsigned) time(NULL)); float x = 0; int i; for(i = 0; i < NSUM; i++) { x += rand() %10; //printf("%f\n",x); }printf("%f\n",x); return (int)(x/NSUM); } int main( int argc, char **argv) { srand((unsigned) time(NULL)); int i, j; int n = 10000, RAN_MAX = 1000, SUM, mod = 100; int *count = malloc(4*mod); for(i=0;i<mod;i++) count[i] = 0; FILE *fp = fopen("tmp.txt","wb"); int min = 9999999, max = -9999999; for(i=0;i<n;i++) { SUM = 0; for(j=0;j<RAN_MAX;j++) { SUM += rand() % mod; } fprintf(fp,"%d\n",SUM); } fclose(fp); fp = fopen("tmp.txt","r"); for(i=0;i<n;i++) { fscanf(fp,"%d\n",&SUM); if(SUM < min) min = SUM; if(SUM > max) max = SUM; } printf("min = %d, max = %d\n",min,max); rewind(fp); for(i=0;i<n;i++) { fscanf(fp,"%d\n",&SUM); SUM = (int)((float)(SUM-min)/(max-min)*mod); count[SUM] ++; } for(i=0;i<mod;i++) { printf("%d\n",count[i]); } return 0; }
中间会生成临时文件“tmp.txt”,里面保存了随机变量的和,我们对这些参数进行“归一化”,并作图得出下图: