环境:QT5+VS2013编译
一、均匀分布
double uniform(double a,double b,long int *seed)
a下限,b上限,seed随机种子。
main.cpp
#include <QCoreApplication> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <uniform.c> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); double b,c,x;int i,j; long int s; double uniform(double,double,long int *); b=0.0;c=1.0;s=13579; for(i=0;i<10;i++) { for(j=0;j<5;j++) { x=uniform(b,c,&s); printf("%13.7f",x); } printf(" "); } return a.exec(); }
uniform.c
double uniform(double a,double b,long int *seed) { double t; *seed=2045*(*seed)+1; *seed=*seed-(*seed/1048576)*1048576; t=(*seed)/1048576.0; t=a+(b-a)*t; return(t); }
二、高斯分布
double gauss(double mean,double sigma,long int *s)
mean位置参数,sigma尺度参数,seed随机种子
main.cpp
#include <QCoreApplication> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <gauss.c> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int i,j; long int s; double x,mean,sigma; double gauss(double,double,long int *); mean=0.0;sigma=1.0;s=13579; for(i=0;i<10;i++) { for(j=0;j<5;j++) { x=gauss(mean,sigma,&s); printf("%13.7f",x); } printf(" "); } return a.exec(); }
gauss.c
#include <uniform.c> double gauss(double mean,double sigma,long int *s) { int i; double x,y; double uniform(double,double,long int *); for(x=0,i=0;i<12;i++) x+=uniform(0.0,1.0,s); x=x-6.0; y=mean+x*sigma; return(y); }
uniform.c
double uniform(double a,double b,long int *seed) { double t; *seed=2045*(*seed)+1; *seed=*seed-(*seed/1048576)*1048576; t=(*seed)/1048576.0; t=a+(b-a)*t; return(t); }