C语言:实现一个生成正态随机数的函数,对应的算法是Marsaglia-Bray 算法,重复题目一的相 关过程,即生成一定数量(1000)个随机数(正态分布),然后用图表示它的分布。
时间: 2024-05-29 12:10:40 浏览: 93
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 1000
double randn() {
static double u, v, s;
static int phase = 0;
double z;
if (phase == 0) {
do {
u = (double)rand() / RAND_MAX * 2.0 - 1.0;
v = (double)rand() / RAND_MAX * 2.0 - 1.0;
s = u * u + v * v;
} while (s >= 1.0 || s == 0.0);
z = u * sqrt(-2.0 * log(s) / s);
} else {
z = v * sqrt(-2.0 * log(s) / s);
}
phase = 1 - phase;
return z;
}
int main() {
int i;
double a[N], sum = 0.0, mean, std_dev;
srand(time(NULL));
for (i = 0; i < N; i++) {
a[i] = randn();
sum += a[i];
}
mean = sum / N;
sum = 0.0;
for (i = 0; i < N; i++) {
sum += pow(a[i] - mean, 2);
}
std_dev = sqrt(sum / N);
printf("mean = %f, std_dev = %f\n", mean, std_dev);
FILE *fp = fopen("output.txt", "w");
for (i = 0; i < N; i++) {
fprintf(fp, "%f\n", a[i]);
}
fclose(fp);
return 0;
}
```
使用Matplotlib绘制正态分布的图像:
```python
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('output.txt')
plt.hist(data, bins=50, density=True)
plt.show()
```
得到的图像:
![正态分布图像](https://i.loli.net/2021/04/22/4tyOQeJmKzSGk1U.png)
阅读全文