用c语言:
如何生成[a,b]范围内服从高斯分布的随机数?
我会生成服从均匀分布的随机数
请大神指点,谢谢!
#include
#include
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
double drand() /* uniform distribution, (0..1] */
{
return (rand()+1.0)/(RAND_MAX+1.0);
}
double random_normal()
/* normal distribution, centered on 0, std dev 1 */
{
return sqrt(-2*log(drand())) * cos(2*M_PI*drand());
}
int main()
{
int i;
double rands[1000];
for (i=0; i<1000; i++)
rands[i] = constMean + constStandardDeviation * random_normal();
return 0;
}
# include "stdio.h"
# include "math.h"
# include "stdlib.h"
# include "math.h"
# include "dos.h"
# define MAX_N 3000 /*这个值为N可以定义的最大长度*/
# define N 100 /*产生随机序列的点数,注意不要大于MAX_N*/
/*1.产生均匀分布的随机变量*/
void randa(float *x,int num);
/*2.产生瑞利分布的随机变量*/
void randr(float *x,int num);
/*3.产生标准高斯分布的随机变量*/
void randn(float *x,int num);
/*4.产生莱斯分布的随机变量*/
void randl(float *x, float a, float b, int num);
void fshow(char *name,float *x,int num);
/***************************************/
int main()
{
float x[N];
int i;
// randa(&x,N); //均匀分布
// randr(&x,N); //瑞利分布
// randl(&x,10,10,N); //莱斯分布
randn(&x,N); //高斯分布
/*此时x[N]表示要生成N个服从xx分布的的数组*/
fshow("x",&x,N); /*显示该序列*/
getch();
return 0;
}
/***************函数定义************************/
/*产生服从均匀分布的随机变量*/
void randa(float *x,int num)
{
int i;
struct time stime;
unsigned seed;
gettime(&stime);
seed=stime.ti_hund*stime.ti_min*stime.ti_hour;
srand(seed);
for(i=0;i<num;i++)
{
x[i]=rand();
x[i]=x[i]/32768;
}
}
/*产生服从瑞利分布的随机变量*/
void randr(float *x,int num)
{
float x1[MAX_N];
int i;
struct time stime;
unsigned seed;
gettime(&stime);
seed=stime.ti_hund*stime.ti_min*stime.ti_hour;
srand(seed);
for(i=0;i<num;i++)
{
x1[i]=rand();
x[i]=x1[i]/32768;
x[i]=sqrt(-2*log(x[i]));
}
}
/*产生服从标准高斯分布的随机变量*/
void randn(float *x,int num)
{
float x1[MAX_N],x2[MAX_N];
int i;
struct time stime;
unsigned seed;
gettime(&stime);
seed=stime.ti_hund*stime.ti_min*stime.ti_hour;
srand(seed);
for(i=0;i<num;i++)
{
x1[i]=rand();
x2[i]=rand();
x1[i]=x1[i]/32768;
x2[i]=x2[i]/32768;
x[i]=sqrt(-2*log(x1[i]))*cos(x2[i]*M_PI);
}
}
/*产生服从莱斯分布的随机变量*/
void randl(float *x, float a, float b, int num)
{
float x1[MAX_N],x2[MAX_N];
float temp[MAX_N];
int i;
struct time stime;
unsigned seed;
gettime(&stime);
seed=stime.ti_hund*stime.ti_min*stime.ti_hour;
srand(seed);
for(i=0;i<num;i++)
{
x1[i]=rand();
x2[i]=rand();
x1[i]=x1[i]/32768;
x2[i]=x2[i]/32768;
temp[i]=sqrt(-2*log(x1[i]))*cos(x2[i]*M_PI);
x2[i]=sqrt(-2*log(x1[i]))*sin(x2[i]*M_PI);
x1[i]=temp[i];
x[i]=sqrt((a+x1[i])*(a+x1[i])+(b+x2[i])*(b+x2[i]));
}
}
void fshow(char *name,float *x,int num)
{
int i,sign,L;
float temp;
printf("\n");
printf(name);
printf(" = ");
L=6;
/*按照每行6个数据的格式显示*/
for(i=0;i<num;i++)
{
temp=i/L;
sign=temp;
if((i-sign*L)==0) printf("\n");
if(x[i]>0) printf(" %f ",x[i]);
else printf("%f ",x[i]);
}
}