SciFEM_Schratter/ex1D_kahan_summation/mylib.cpp

34 lines
No EOL
872 B
C++

#include "mylib.h"
#include <cassert> // assert()
#include <cmath>
#include <vector>
using namespace std;
double scalar(vector<double> const &x, vector<double> const &y)
{
assert(x.size() == y.size());
size_t const N = x.size();
double sum = 0.0;
for (size_t i = 0; i < N; ++i)
{
sum += x[i] * y[i];
}
return sum;
}
double Kahan_skalar(vector<double> const &x, vector<double> const &y)
{
double sum = 0;
double c = 0;
size_t n = x.size();
for (size_t i = 0; i < n; ++i)
{
double z = x[i]*y[i] - c; // c is the part that got lost in the last iteration
double t = sum + z; // when adding sum + z, the lower digits are lost if sum is large
c = (t - sum) - z; // now we recover the lower digits to add in the next iteration
sum = t;
}
return sum;
}