Skip to content

Instantly share code, notes, and snippets.

@John-Colvin
Last active October 1, 2015 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save John-Colvin/a57d1754f266fba96519 to your computer and use it in GitHub Desktop.
Save John-Colvin/a57d1754f266fba96519 to your computer and use it in GitHub Desktop.
pairWise summation for input ranges
/++
$(LUCKY Pairwise summation) algorithm. Range must be a finite range.
+/
private F sumPairwise(Range, F = Unqual!(ForeachType!Range))(Range data)
if (isInputRange!Range && !isInfinite!Range)
{
import core.bitop : bsf;
// Works for r with length < 2^^64, in keeping with the use of size_t
// elsewhere in std.algorithm and std.range on 64 bit platforms.
F[64] store = F.max;
size_t idx = 0;
foreach (i, el; enumerate(data))
{
store[idx] = el;
foreach (_; 0 .. (i+1).bsf)
{
store[idx - 1] += store[idx];
--idx;
}
++idx;
}
F s = store[idx - 1];
foreach_reverse (i; 0 .. idx - 1)
s += store[i];
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment