Upload files to "ex1D_kahan_summation"
This commit is contained in:
parent
c70572f1b9
commit
9098bcc99a
3 changed files with 97 additions and 0 deletions
34
ex1D_kahan_summation/mylib.cpp
Normal file
34
ex1D_kahan_summation/mylib.cpp
Normal 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue