Upload files to "ex1D_kahan_summation"

This commit is contained in:
Jakob Schratter 2025-10-22 15:22:37 +02:00
commit 9098bcc99a
3 changed files with 97 additions and 0 deletions

View file

@ -0,0 +1,34 @@
#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;
}