#include <numeric>
#include <iostream>
#include <vector>
struct KahanAccumulation
{
double sum;
double correction;
};
KahanAccumulation KahanSum(KahanAccumulation accumulation, double value)
{
KahanAccumulation result;
double y = value - accumulation.correction;
double t = accumulation.sum + y;
result.correction = (t - accumulation.sum) - y;
result.sum = t;
return result;
}
int main()
{
std::vector<double> numbers = {0.01, 0.001, 0.0001, 0.000001, 0.00000000001};
KahanAccumulation init = {0};
KahanAccumulation result =
std::accumulate(numbers.begin(), numbers.end(), init, KahanSum);
std::cout << "Kahan Sum: " << result.sum << std::endl;
return 0;
}
I2luY2x1ZGUgPG51bWVyaWM+CiNpbmNsdWRlIDxpb3N0cmVhbT4KI2luY2x1ZGUgPHZlY3Rvcj4KCnN0cnVjdCBLYWhhbkFjY3VtdWxhdGlvbgp7CiAgICBkb3VibGUgc3VtOwogICAgZG91YmxlIGNvcnJlY3Rpb247Cn07CgpLYWhhbkFjY3VtdWxhdGlvbiBLYWhhblN1bShLYWhhbkFjY3VtdWxhdGlvbiBhY2N1bXVsYXRpb24sIGRvdWJsZSB2YWx1ZSkKewogICAgS2FoYW5BY2N1bXVsYXRpb24gcmVzdWx0OwogICAgZG91YmxlIHkgPSB2YWx1ZSAtIGFjY3VtdWxhdGlvbi5jb3JyZWN0aW9uOwogICAgZG91YmxlIHQgPSBhY2N1bXVsYXRpb24uc3VtICsgeTsKICAgIHJlc3VsdC5jb3JyZWN0aW9uID0gKHQgLSBhY2N1bXVsYXRpb24uc3VtKSAtIHk7CiAgICByZXN1bHQuc3VtID0gdDsKICAgIHJldHVybiByZXN1bHQ7Cn0KCmludCBtYWluKCkKewogICAgc3RkOjp2ZWN0b3I8ZG91YmxlPiBudW1iZXJzID0gezAuMDEsIDAuMDAxLCAwLjAwMDEsIDAuMDAwMDAxLCAwLjAwMDAwMDAwMDAxfTsKICAgIEthaGFuQWNjdW11bGF0aW9uIGluaXQgPSB7MH07CiAgICBLYWhhbkFjY3VtdWxhdGlvbiByZXN1bHQgPQogICAgICAgIHN0ZDo6YWNjdW11bGF0ZShudW1iZXJzLmJlZ2luKCksIG51bWJlcnMuZW5kKCksIGluaXQsIEthaGFuU3VtKTsKCiAgICBzdGQ6OmNvdXQgPDwgIkthaGFuIFN1bTogIiA8PCByZXN1bHQuc3VtIDw8IHN0ZDo6ZW5kbDsKICAgIHJldHVybiAwOwp9