function [s_hat, e] = compSum(x)

%COMPSUM Compensated summation COMPSUM(X) computes the compensated sum
%        of the input matrix X via Kahan's algorithm
%        The compensated sum is returned in S.
%        The error estimate for S is returned in E.

if (~isvector(x)),
  error('*ERR* At present, compSum only accepts vector arguments.')
end

m = length(x);

s_hat = 0; e = 0;        % initialize sum and error

for i=1:m,
  a = s_hat;             % a stands for the sum to this point
  b = x(i) + e;          % get the next element and compensate
  s_hat = a + b;         % add b to the sum
  e = (a - s_hat) + b;   % compute error estimate
end