c++写一个野值剔除算法
时间: 2024-05-15 16:12:57 浏览: 12
野值剔除算法是通过排除数据集中远离平均值的异常值来减少数据误差的一种方法。常见的算法包括3σ原则和箱线图法。
以下是使用3σ原则的C++代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int n = 10; // 数据量
double data[n] = {1.2, 2.3, 1.5, 4.2, 5.1, 1.2, 3.4, 2.9, 2.5, 2.8}; // 数据集
double sum = 0; // 总和
for(int i = 0; i < n; i++)
{
sum += data[i];
}
double avg = sum / n; // 平均值
double variance = 0; // 方差
for(int i = 0; i < n; i++)
{
variance += (data[i] - avg) * (data[i] - avg);
}
variance /= n;
double std_deviation = sqrt(variance); // 标准差
double lower_bound = avg - 3 * std_deviation; // 下限
double upper_bound = avg + 3 * std_deviation; // 上限
for(int i = 0; i < n; i++)
{
if(data[i] < lower_bound || data[i] > upper_bound)
{
cout << "Warning: the data point " << data[i] << " is an outlier!" << endl;
}
}
return 0;
}
```
在以上代码中,我们先求出数据集的平均值和标准差,然后根据3σ原则计算出上下限,最后判断数据点是否超出上下限,如果超出,则被视为异常值。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)