一个用C++实现的计算斜率的函数,跟Excel的Slope的计算结果一致,示例如下:
使用自定义C++函数计算结果如下:
完整代码如下:
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
//判断double类型变量是否等于0
#define ISZERO(x) ((fabs(x) < 1e-6) ? true : false)
//计算斜率的函数
// @param vc:参与计算斜率的数字数组,从后向前取最新的nPeroid个数字计算
// @param nPeriod: 计算斜率的周期
double Slope(std::vector<double>& vc, int nPeriod)
{
?????? int sz = (int)vc.size();
?????? if (sz < nPeriod) { return 0; }
?????? double xsum = 0;
?????? double ysum = 0;
?????? double xxsum = 0;
?????? double xysum = 0;
?????? int i = 0, nBegin = sz - nPeriod;
?????? for (i = 0; i < nPeriod; ++i)
?????? {
????????????? xsum += i;
????????????? ysum += vc[nBegin + i];
????????????? xxsum += (1.0 * i) * i;
????????????? xysum += i * vc[nBegin + i];
?????? }
?????? double tmp = (xxsum - (xsum / nPeriod) * xsum);
?????? if (ISZERO(tmp)) { return 0; }
?????? return (xysum - (ysum / nPeriod) * xsum) / tmp;
}
//测试代码
int main()
{
?????? std::vector<int32_t> vc;
?????? vc.push_back(10);
?????? vc.push_back(11);
?????? vc.push_back(12);
?????? vc.push_back(13);
?????? vc.push_back(14);
?????? vc.push_back(15);
?????? vc.push_back(16);
?????? vc.push_back(16);
?????? vc.push_back(15);
?????? vc.push_back(14);
?????? vc.push_back(14);
?????? vc.push_back(12);
?????? vc.push_back(11);
?????? vc.push_back(11);
?????? vc.push_back(11);
?????? vc.push_back(10);
?????? vc.push_back(9);
?????? vc.push_back(8);
?????? vc.push_back(7);
?????? vc.push_back(6);
?????? vc.push_back(5);
?????? vc.push_back(4);
?????? vc.push_back(3);
?????? vc.push_back(2);
?????? vc.push_back(1);
??????
?????? std::vector<double> vcTmp;
?????? std::vector<double> vcSlope;
?????? for (size_t i = 0; i < vc.size(); ++i)
?????? {
????????????? vcTmp.push_back(vc[i]);
????????????? double dSlope = Slope(vcTmp, 4);
????????????? vcSlope.push_back(dSlope);
?????? }
?????? for (size_t i = 0; i < vcSlope.size(); ++i)
?????? {
????????????? printf("%-6d %-6d %.2lf\n", i, vc[i], vcSlope[i]);
?????? }
?????? return 0;
}