用c++语言验证中心极限定理 第一步:构造含N个个体的总体(例如 均匀分布 1~100000的十万个自然数,或者是每个数出现的频数等于数值的一组数)并计算总体的均值与方差 第二步:确定样本量n以及抽样的样本数m 第三步:重复抽样m次,每次从N个总体中抽取n个个体作为一个样本,计算样本均值 第四步:计算第三步获得的m个样本均值的平均值和方差 第五步:验证第四步获得的均值是否等于总体的均值 验证第四步获得的方差是否等于总体方差的n分之一
时间: 2023-05-30 10:06:15 浏览: 119
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define N 100000 // 总体中的个体数
#define MAX_SAMPLE_NUM 10000 // 最大抽样次数
#define SAMPLE_SIZE 100 // 每个样本中个体的数量
int population[N]; // 总体数组
double population_mean = 0.0; // 总体均值
double population_variance = 0.0; // 总体方差
int sample_count = 0; // 抽样次数
double sample_means[MAX_SAMPLE_NUM]; // 每个样本的均值
void construct_population() { // 构造总体数组
int i;
for (i = 0; i < N; i++) {
population[i] = i + 1;
}
}
void calculate_population_mean_and_variance() { // 计算总体均值和方差
int i;
for (i = 0; i < N; i++) {
population_mean += population[i];
}
population_mean /= N;
for (i = 0; i < N; i++) {
population_variance += pow(population[i] - population_mean, 2);
}
population_variance /= N;
}
void sampling() { // 抽样
int i, j;
double sample_mean;
srand((unsigned int) time(NULL));
for (i = 0; i < MAX_SAMPLE_NUM; i++) {
sample_mean = 0.0;
for (j = 0; j < SAMPLE_SIZE; j++) {
sample_mean += population[rand() % N];
}
sample_mean /= SAMPLE_SIZE;
sample_means[i] = sample_mean;
}
sample_count = MAX_SAMPLE_NUM;
}
double calculate_sample_means_mean() { // 计算样本均值的均值
int i;
double sample_means_mean = 0.0;
for (i = 0; i < sample_count; i++) {
sample_means_mean += sample_means[i];
}
sample_means_mean /= sample_count;
return sample_means_mean;
}
double calculate_sample_means_variance() { // 计算样本均值的方差
int i;
double sample_means_variance = 0.0;
for (i = 0; i < sample_count; i++) {
sample_means_variance += pow(sample_means[i] - population_mean, 2);
}
sample_means_variance /= sample_count * SAMPLE_SIZE;
return sample_means_variance;
}
int main() {
construct_population();
calculate_population_mean_and_variance();
sampling();
double sample_means_mean = calculate_sample_means_mean();
double sample_means_variance = calculate_sample_means_variance();
printf("Population mean: %lf\n", population_mean);
printf("Sample means mean: %lf\n", sample_means_mean);
printf("Sample means variance: %lf\n", sample_means_variance);
printf("Sample means mean equals population mean? %s\n", fabs(sample_means_mean - population_mean) < 0.00001 ? "Yes" : "No");
printf("Sample means variance equals population variance / n? %s\n", fabs(sample_means_variance - population_variance / SAMPLE_SIZE) < 0.00001 ? "Yes" : "No");
return 0;
}
阅读全文