使用C++实现Excel中的stdev.p函数,用来计算标准差。Excel计算示例如下:周期为5。
使用自定义的C++函数计算,运行结果如下:
完整的可运行代码如下:
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
//标准差计算函数
double StdEvP(std::vector<double>& vc, int nPeriod)
{
?????? if (nPeriod <= 0) { return 0; }
?????? int sz = (int)vc.size();
?????? if (sz < nPeriod) { return std::nan(""); }
?????? int i = 0, nBegin = sz - nPeriod;
?????? // 计算均值
?????? double dbAvg = 0;
?????? for (i = sz - 1; i >= nBegin; --i)
?????? {
????????????? dbAvg += vc[i];
?????? }
?????? dbAvg /= nPeriod;
?????? // 计算方差的和
?????? double dbStdDev = 0;
?????? for (i = sz - 1; i >= nBegin; --i)
?????? {
????????????? dbStdDev += pow((vc[i] - dbAvg), 2);
?????? }
?????? // 计算平均方差
?????? dbStdDev /= nPeriod;
?????? // 计算标准差
?????? dbStdDev = sqrt(dbStdDev);
?????? return dbStdDev;
}
//测试程序
int main()
{
?????? int num[] = { 1,2,3,4,5,6,7,8,9,10,10,10,11,10,10,9,8,7,6,5,4,3,2,1,1,5,6,7,8,9 };
?????? std::vector<double> vcTmp;
?????? std::vector<double> vcStd;
?????? for (int i = 0; i < sizeof(num) / sizeof(int); ++i)
?????? {
????????????? vcTmp.push_back(num[i]);
????????????? double stdevp = StdEvP(vcTmp, 5);
????????????? vcStd.push_back(stdevp);
?????? }
?????? for (size_t i = 0; i < vcTmp.size(); ++i)
?????? {
????????????? if (isnan(vcStd[i]))
????????????? {
???????????????????? printf("%-6d\n", num[i]);
????????????? }
????????????? else
????????????? {
???????????????????? printf("%-6d %.3lf\n", num[i], vcStd[i]);
????????????? }
?????????????
?????? }
?????? return 0;
}