z-score标准化 C代码
时间: 2023-03-20 17:02:32 浏览: 82
以下是z-score标准化的C代码示例:
```
#include <stdio.h>
#include <math.h>
void standardize(double arr[], int size) {
double sum = 0.0, mean, sd;
int i;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
mean = sum / size;
sum = 0.0;
for (i = 0; i < size; ++i) {
sum += pow(arr[i] - mean, 2);
}
sd = sqrt(sum / size);
for (i = 0; i < size; ++i) {
arr[i] = (arr[i] - mean) / sd;
}
}
int main() {
double arr[] = {2.3, 3.5, 1.2, 5.6, 4.4};
int size = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Original array: ");
for (i = 0; i < size; ++i) {
printf("%.2f ", arr[i]);
}
standardize(arr, size);
printf("\nStandardized array: ");
for (i = 0; i < size; ++i) {
printf("%.2f ", arr[i]);
}
return 0;
}
```
这段代码中,standardize函数将传入的数组进行z-score标准化,即将每个元素减去平均值,然后除以标准差。main函数中则定义了一个测试数组,调用standardize函数进行标准化,并打印出标准化前后的数组。
阅读全文