在本教程中,我们将讨论实现t检验的程序。
学生的T检验的t检验用于比较两个均值,并判断两者是否相似或不同。与此同时,t检验还有助于确定差异的大小,以了解更改的原因。
#include <bits/stdc++.h> using namespace std; //计算均值 float calc_mean(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + arr[i]; return sum / n; } //计算标准偏差 float calc_deviation(float arr[], int n){ float sum = 0; for (int i = 0; i < n; i++) sum = sum + (arr[i] - calc_mean(arr, n)) * (arr[i] - calc_mean(arr, n)); return sqrt(sum / (n - 1)); } //查找两个数据的t检验 float calc_ttest(float arr1[], int n, float arr2[], int m){ float mean1 = calc_mean(arr1, n); float mean2 = calc_mean(arr2, m); float sd1 = calc_deviation(arr1, n); float sd2 = calc_deviation(arr2, m); float t_test = (mean1 - mean2) / sqrt((sd1 * sd1) / n + (sd2 * sd2) / m); return t_test; } int main(){ float arr1[] = { 10, 20, 30, 40, 50 }; int n = sizeof(arr1) / sizeof(arr1[0]); float arr2[] = { 1, 29, 46, 78, 99 }; int m = sizeof(arr2) / sizeof(arr2[0]); cout << calc_ttest(arr1, n, arr2, m) << endl; return 0; }
输出结果
-1.09789