Hello,
I'm new to C++ and I'm trying to create an exponential moving average using vectors. When I push values onto the vector I'm getting arbitrary values when I read the resulting vector elements. Here's the code snippet:
void EMA(vector<double> prices) {
vector<double> expMA;
int i = 0;
double fma = 0.0;
double sum = 0.0;
double ema = 0.0;
double multiplier = 0.0;
const int period = 10;
multiplier = 2.0 / (period + 1);
// calculate first ema value
for (i = 0; i <= period; i++) {
sum = sum + prices;
}
fma = sum / (period);
expMA.push_back(fma);
for (i = 0; i < prices.size() - period; i++) {
ema = multiplier*(prices[i + period] - expMA) - expMA;
expMA.push_back(ema);
}
//print out of EMA values
for (unsigned int i = 0; i < expMA.size(); i++) {
cout << expMA << endl;
}
}
What would cause the vector to misbehave?
Thanks for your help,
TJ
I'm new to C++ and I'm trying to create an exponential moving average using vectors. When I push values onto the vector I'm getting arbitrary values when I read the resulting vector elements. Here's the code snippet:
void EMA(vector<double> prices) {
vector<double> expMA;
int i = 0;
double fma = 0.0;
double sum = 0.0;
double ema = 0.0;
double multiplier = 0.0;
const int period = 10;
multiplier = 2.0 / (period + 1);
// calculate first ema value
for (i = 0; i <= period; i++) {
sum = sum + prices;
}
fma = sum / (period);
expMA.push_back(fma);
for (i = 0; i < prices.size() - period; i++) {
ema = multiplier*(prices[i + period] - expMA) - expMA;
expMA.push_back(ema);
}
//print out of EMA values
for (unsigned int i = 0; i < expMA.size(); i++) {
cout << expMA << endl;
}
}
What would cause the vector to misbehave?
Thanks for your help,
TJ