計算一個序列的移動平均線序列的模板,可實現均線的均線

來源:互聯網
上載者:User

標籤:==   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);//均線的均線的均線

計算一個序列的移動平均線序列的模板,可實現均線的均線

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.