fork(9) download
  1. #include <numeric>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. struct KahanAccumulation
  6. {
  7. double sum;
  8. double correction;
  9. };
  10.  
  11. KahanAccumulation KahanSum(KahanAccumulation accumulation, double value)
  12. {
  13. KahanAccumulation result;
  14. double y = value - accumulation.correction;
  15. double t = accumulation.sum + y;
  16. result.correction = (t - accumulation.sum) - y;
  17. result.sum = t;
  18. return result;
  19. }
  20.  
  21. int main()
  22. {
  23. std::vector<double> numbers = {0.01, 0.001, 0.0001, 0.000001, 0.00000000001};
  24. KahanAccumulation init = {0};
  25. KahanAccumulation result =
  26. std::accumulate(numbers.begin(), numbers.end(), init, KahanSum);
  27.  
  28. std::cout << "Kahan Sum: " << result.sum << std::endl;
  29. return 0;
  30. }
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
Kahan Sum: 0.011101