Skip to content

Instantly share code, notes, and snippets.

@John-Colvin
Created September 22, 2015 11:20
Show Gist options
  • Save John-Colvin/8f6b63011e66c38067f5 to your computer and use it in GitHub Desktop.
Save John-Colvin/8f6b63011e66c38067f5 to your computer and use it in GitHub Desktop.

A draft example of kahan sum as an input/forward range (I'm using double just to make it a simple example):

struct KahanSum(R)
{
    R r;
    double sum = 0.0;
    double c = 0.0;
    this(R r)
    {
        this.r = r;
        sum = r.front;
        r.popFront();
    }
    auto front() @property
    {
        return sum;
    }
    bool empty() @property
    {
        return r.empty;
    }
    void popFront()
    {
        double y = r.front - c;
        double t = sum + y;
        c = (t - sum) - y;
        sum = t;
    }
    static if(isForwardRange!R) auto save() @property
    {
        auto tmp = this;
        tmp.r = r.save;
        return tmp;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment