用C语言写一份程序,从0~100的均匀分布中进行抽样,获取其均值,得到10000个均值,并且输出均值在40~60之间以0.2为区间上的概率分布
时间: 2024-10-02 16:02:53 浏览: 53
在C语言中,我们可以使用rand()函数生成0到RAND_MAX(通常是32767)之间的伪随机数,然后通过一些算法调整使其近似于均匀分布在0到100之间。接下来,我们需要计算这10000次抽样中落在40到60范围内的平均值,以及相应的频率,以此估算概率分布。
首先,确保已包含 `<stdlib.h>` 和 `<time.h>` 头文件,因为rand()函数在此头文件中声明:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
const int sample_size = 10000;
const int range_min = 0;
const int range_max = 100;
const double interval_width = 2.0;
double sum_in_range = 0;
double total_samples = 0;
// 设置随机数种子以保证每次运行结果一致(这里用当前时间)
srand(time(0));
for (int i = 0; i < sample_size; ++i) {
// 抽取样本
int sample = rand() % (range_max - range_min + 1) + range_min;
// 如果样本在40到60范围内,累加并计数
if (sample >= 40 && sample <= 60) {
sum_in_range += sample;
total_samples++;
}
}
// 计算均值
double mean_in_range = sum_in_range / total_samples;
printf("Mean of samples in the range 40 to 60: %.2f\n", mean_in_range);
// 计算概率分布(假设区间长度固定)
double probability = (total_samples == 0) ? 0 : ((double)total_samples / sample_size);
printf("Probability distribution within the interval 40 to 60 with a step of 0.2:\n");
for (int j = 40; j <= 60; j += interval_width) {
double lower_bound = j - interval_width / 2;
double upper_bound = j + interval_width / 2;
if (lower_bound >= 0 && upper_bound <= 100) {
printf("%.2f - %.2f: %.2f%%\n", lower_bound, upper_bound, probability * 100);
} else {
printf("Range out of bounds at %d\n", j);
}
}
return 0;
}
```
阅读全文
相关推荐
















