标题:
C语言与数字信号处理——正态分布的随机数
[打印本页]
作者:
look_w
时间:
2017-11-18 20:04
标题:
C语言与数字信号处理——正态分布的随机数
1. 公式
概率密度函数:
f
(
x
)
=
1
σ
2
π
−
−
√
e
−
(
x
−
μ
)
2
2
σ
2
均值:
E
[
X
]
=
μ
方差:
V
A
R
[
X
]
=
σ
2
2. C代码生成随机数
C代码
double Gauss(double mean, double sigma, long int * seed){ static double V1, V2, S; static int phase = 0; double X,U1,U2; if ( phase == 0 ) { do { U1 = Uniform(0.0, 1.0, seed); U2 = Uniform(0.0, 1.0, seed); V1 = 2 * U1 - 1; V2 = 2 * U2 - 1; S = V1 * V1 + V2 * V2; } while(S >= 1 || S == 0); X = V1 * sqrt(-2 * log(S) / S); } else X = V2 * sqrt(-2 * log(S) / S); phase = 1 - phase; X = X * sigma + mean; return X;}参数说明:
mean:正态分布的均值
μ
sigma:正态分布的均方差
σ
*seed:随机数的种子
生成1000个均值为0,方差为1的随机数:
void main(void){ long int seed = 13579; int j, num; double mean, sigma, temp; FILE * fp; mean = 0; sigma = 1; num = 1000; fp = fopen("gauss.dat", "w"); for (j = 0; j < num; j++) { temp = Gauss(a, b, &seed); fprintf(fp, "%10.7f\n", temp); } fclose(fp);}3. 对比matlab的生成结果
用matlab生成相同数量的随机数,对比概率密度估计:
num = 1000;mean = 0;sigma = 1;% 绘制概率密度函数x = -(sigma*3+1):0.01
sigma*3+1);y = normpdf(x,mean,sigma); figure(1); plot(x,y); % 绘制随机数对比图z1 = VarName1;z2 = normrnd(mean,sigma,1,num); x1 = 0:1
num-1);figure(2); plot(x1, z1, 'r.', x1, z2, 'b.');% 绘制概率密度估计对比图y1 = ksdensity(z1);y2 = ksdensity(z2);figure(3);plot(y1,'DisplayName','gauss');hold on;plot(y2,'DisplayName','normrnd');
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/)
Powered by Discuz! 7.0.0