標籤:== else nload cto 實現 代碼 sum ack 優點
#pragma once
//write by 陳墨仙 20150718
//功能:計算序列的移動平均線,並返回序列
template<class T>class funcMa
{
public:
funcMa(){lastTick = 0;};
~funcMa(){};
void clear()
{
t.clear();
t.swap(vector<T>(t));
lastTick = 0;
}
vector<T> Caculate(vector<T> p,int N,int direction)
{
int size = p.size() -1;
if (size <= 0)
{
return t;
}
//vector<double> tSum;
if (direction == 1)
{
for (;size > lastTick; size--)
{
T sum = 0;
T ma = 0;
if(N > size)
{
N = size + 1;
}
for (int i = size; i > size - N; i--)
{
sum += p[i];
}
ma = sum/N;
//tSum.push_back(sum);
t.push_back(ma);
}
lastTick = size + 1;
}
else
{
for (int i = lastTick; i<=size; i++)
{
T sum = 0;
T ma =0;
int temp = N;
if(temp > i)
temp = i + 1;
for(int j = i; j > i - temp; j--)
{
sum+=p[j];
}
ma = sum/temp;
t.push_back(ma);
}
lastTick = size + 1;
}
return t;
}
private:
int lastTick;
vector<T> t;
};
源碼:http://download.csdn.net/detail/corivsky/8916855
該代碼的優點是。僅僅要不clear,就不會反覆計算移動平均序列,當傳入序列增大時。他會在原有基礎上計算傳入序列新增的數值。
用法:static funcMa<double> ma60;static funcMa<double> ma2;static funcMa<double> ma22;static vector<double> C;//收盤價序列vector<double> ma60temp = ma60.Caculate(C,N*2,0);//收盤價的均線序列vector<double> ma2temp = ma2.Caculate(ma60temp,M1*2,0);//均線的均線vector<double> ma22temp =ma22.Caculate(ma2temp,M2*2,0);//均線的均線的均線
計算一個序列的移動平均線序列的模板,可實現均線的均線