使用模板如何计算 x 个数字的平均值?
Using templates how can I calculate the average of x numbers?
所以我 statistics.h 有了这个
template<typename T>
class OwnType {
public:
OwnType() {};
virtual ~OwnType() {};
void nextValue(T value) {
nmbrCnt++;
cout << "Value: " << value << endl;
cout << "# of Values so far: " << nmbrCnt << endl;
average = (average + value) / nmbrCnt; // calculate average <----- WRONG!
variance += pow(value - average, 2) / nmbrCnt; // calculate standard variance/deviation
};
T getAverage() { return average; }
T getVariance() { return variance; }
T getRange() { return max - min; }
private:
T max = NULL;
T min = NULL;
T average = NULL;
double variance = 0;
int nmbrCnt = 0;
bool firstCall = true;
};
在 main.cpp 我这样做:
void main() {
OwnType<double> list;
list.nextValue(10.5);
cout << "Average: " << list.getAverage() << endl;
list.nextValue(5);
cout << "Average: " << list.getAverage() << endl;
list.nextValue(3);
cout << "Average: " << list.getAverage() << endl;
list.nextValue(24.6)
cout << "Average: " << list.getAverage() << endl;
}
但是,似乎存在逻辑错误或者我没有正确理解模板。我可以很好地计算平均值,如果它在数组中,但没有数组,没有任何存储,我很难过。有开斋吗?
您的 运行 均值和方差公式不正确。
我的 Monte Carlo 库中的一些代码可以帮助您:
// Running variance calculation requires the previous value of the
// mean so we do this one first.
variance = path > 1 ?
(path - 1.0) / path * (variance + (mean - pv) * (mean - pv) / path) :
0.0;
mean = ((path - 1.0) * mean + pv) / path;
此处,pv
是要添加的新值,path
合并新值后分布中值的数量。
如果 T
是整数类型,那么要小心整数除法的截断效应。您的 运行 均值和方差会因截断而恶化。
更好的是,完全放弃模板并使用 double
。
所以我 statistics.h 有了这个
template<typename T>
class OwnType {
public:
OwnType() {};
virtual ~OwnType() {};
void nextValue(T value) {
nmbrCnt++;
cout << "Value: " << value << endl;
cout << "# of Values so far: " << nmbrCnt << endl;
average = (average + value) / nmbrCnt; // calculate average <----- WRONG!
variance += pow(value - average, 2) / nmbrCnt; // calculate standard variance/deviation
};
T getAverage() { return average; }
T getVariance() { return variance; }
T getRange() { return max - min; }
private:
T max = NULL;
T min = NULL;
T average = NULL;
double variance = 0;
int nmbrCnt = 0;
bool firstCall = true;
};
在 main.cpp 我这样做:
void main() {
OwnType<double> list;
list.nextValue(10.5);
cout << "Average: " << list.getAverage() << endl;
list.nextValue(5);
cout << "Average: " << list.getAverage() << endl;
list.nextValue(3);
cout << "Average: " << list.getAverage() << endl;
list.nextValue(24.6)
cout << "Average: " << list.getAverage() << endl;
}
但是,似乎存在逻辑错误或者我没有正确理解模板。我可以很好地计算平均值,如果它在数组中,但没有数组,没有任何存储,我很难过。有开斋吗?
您的 运行 均值和方差公式不正确。
我的 Monte Carlo 库中的一些代码可以帮助您:
// Running variance calculation requires the previous value of the
// mean so we do this one first.
variance = path > 1 ?
(path - 1.0) / path * (variance + (mean - pv) * (mean - pv) / path) :
0.0;
mean = ((path - 1.0) * mean + pv) / path;
此处,pv
是要添加的新值,path
合并新值后分布中值的数量。
如果 T
是整数类型,那么要小心整数除法的截断效应。您的 运行 均值和方差会因截断而恶化。
更好的是,完全放弃模板并使用 double
。