生成正态随机分布数

double Normal_rand(double u, double d, int nnum_i)
{//生成一个以u为均值,d为均方差的正态随机数,大数取nnum_i
 
    if(d<=0)return(u);
 
    int nnum=nnum_i;
    double sum_nnum=0.0;
    int i;
    //srand((unsigned)time(NULL));
    for(i=0;i<nnum;i++)
    {   
        sum_nnum+=(double)rand()/RAND_MAX;
    }
    ///////////////////////////
    //以下采取了中心极限定理,
    //由多个均匀分布产生服从正态的随机数,
    //均匀分布均值是0.5,方差是1/12,
    //n个均匀分布的随机变量和减(n*0.5)
    //再除以根号下n*(1/12)应当近似服从N(0,1),
    //在此n取nnum
    //////////////////////////
    return(u+d*(sum_nnum-nnum/2)/(double)sqrt(nnum/12));
}
 
double Normal_rand(double u,double d)
{//生成一个以u为均值,d为均方差的正态随机数x,采用反函数法   
    double u1,u2,z,x;
     
    if(d<=0)return(u);
 
    u1=(double)rand()/(double)RAND_MAX;
    u2=(double)rand()/(double)RAND_MAX;
 
    if(u1>0.0000000000000000)
    z=sqrt(-2*log(u1))*sin(2*Pi*u2);
    else z=0;
    x=u+d*z;
 
    return(x);
}

你可能感兴趣的:(生成正态随机分布数)