English

## Does iMAOnArray give the true result ?

 2 bertrand125 2015.05.07 16:05   I try to compute MA to check if the fuction iMAOnArray gives the true result. I find the same result for SMA, but not for EMA, can someone check my code ? ```double iMAOnArray2(double       array[],          // array with data                    int          total,            // number of elements                    int          ma_period,        // MA averaging period                    int          ma_shift,         // MA shift                    int          ma_method,        // MA averaging method                    int          shift             // shift)                   ) {   int n = ArraySize(array) - ma_shift;   int i,j;   double sum = 0;   double priceprec,price;      switch(ma_method) {   case MODE_SMA:     for(i = n-1-shift; i >= n-ma_period-1; i--) {       if(i >= 0) sum+=array[i];       else return 0;     }     return sum / (ma_period - j);   break;      case MODE_EMA:     price = 0;     double pr = 2.0/(ma_period+1);     for(i = n-ma_period-1; i <= n-1-shift; i++) {       if(i == n-ma_period-1) price = array[i];       else {         price = array[i]*pr+priceprec*(1-pr);       }       priceprec = price;     }     return price;   break;      case MODE_SMMA:      break;      case MODE_LWMA:      break;   }      }```
 12983 WHRoeder 2015.05.07 20:04 #   bertrand125: I try to compute MA to check if the fuction iMAOnArray gives the true result. I find the same result for SMA, but not for EMA, can someone check my code ? ```    for(i = n-ma_period-1; i <= n-1-shift; i++) {       if(i == n-ma_period-1) price = array[i];       else {         price = array[i]*pr+priceprec*(1-pr);       }       priceprec = price;     }```I assume your array is timeseries (a buffer,) so you need to loop from [n-1 .. shift] so your i <= n-1-shift means no loop. bogusThere is no need to not use the first ma_period values.a[]*pr + prev*(1-pr) magnifies round off error. Use the form below which fades round off errors. Moving average - Wikipedia, the free encyclopedia```i = n - 1; price = array[i]; while(--i >= shift) price += ( array[i] - price )*pr;```