Skip to content

Instantly share code, notes, and snippets.

@ziotom78
Created June 22, 2012 11:06
Show Gist options
  • Save ziotom78/2972118 to your computer and use it in GitHub Desktop.
Save ziotom78/2972118 to your computer and use it in GitHub Desktop.
Mean calculation test
#include <iostream>
#include <vector>
template<typename T> T
mean_with_accumulator(const std::vector<T> & vec)
{
T acc = 0.0;
for(T cur_element : vec)
acc += cur_element;
return acc/vec.size();
}
template<typename T> T
mean_without_accumulator(const std::vector<T> & vec)
{
T mean = 0.0;
for(size_t index = 0; index < vec.size(); ++index)
mean += (vec[index] - mean) / (index + 1);
return mean;
}
template<typename T> T
mean_with_Kahan_sum(const std::vector<T> & vec)
{
T sum = 0.0;
T correction = 0.0;
for(size_t index = 0; index < vec.size(); ++index)
{
T cur_element_corrected = vec[index] - correction;
T new_sum = sum + cur_element_corrected;
correction = (new_sum - sum) - cur_element_corrected;
sum = new_sum;
}
return sum/vec.size();
}
template<typename T> void
run_test()
{
const int num = 10000000;
std::vector<T> v;
v.resize(num);
for(int i = 0; i < num; ++i)
v[i] = 4.5 + ((T) i) / (num - 1);
std::cout.precision(10);
std::cout << "Floating point size: " << sizeof(T) << " bytes \n"
<< " Expected result: 5.0\n"
<< " Mean with accumulator: " << mean_with_accumulator(v) << "\n"
<< " Without accumulator: " << mean_without_accumulator(v) << "\n"
<< " Kahan sum: " << mean_with_Kahan_sum(v);
std::cout << "\n" << std::endl;
}
int main(int argc, char **argv)
{
run_test<float>();
run_test<double>();
run_test<long double>();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment