Exercise 4, Sheet 1
This commit is contained in:
parent
ff2fb3cca4
commit
b02c1718a0
1 changed files with 57 additions and 0 deletions
57
mainEx4.cpp
Normal file
57
mainEx4.cpp
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
#include <iostream>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cassert>
|
||||||
|
#include <vector>
|
||||||
|
#include <iomanip>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
double NormalSeries(size_t N)
|
||||||
|
{
|
||||||
|
double sum = 0.0;
|
||||||
|
for (size_t i = 1; i <= N; ++i)
|
||||||
|
{
|
||||||
|
sum += 1.0 / (double(i) * double(i));
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
double KahanSeries(size_t N)
|
||||||
|
{
|
||||||
|
double sum = 0.0;
|
||||||
|
double c = 0.0;
|
||||||
|
for (size_t i = 1; i <= N; ++i) {
|
||||||
|
double term = 1.0 / (double(i) * double(i));
|
||||||
|
double y = term - c;
|
||||||
|
double t = sum + y;
|
||||||
|
c = (t - sum) - y;
|
||||||
|
sum = t;
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
const double pi2_over_6 = (M_PI * M_PI) / 6.0;
|
||||||
|
// vector<size_t> ns = {10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
|
||||||
|
vector<size_t> ns = {1000000, 10000000, 100000000, 500000000, 1000000000};
|
||||||
|
|
||||||
|
|
||||||
|
for (size_t n : ns)
|
||||||
|
{
|
||||||
|
double s_norm = NormalSeries(n);
|
||||||
|
double s_kahan = KahanSeries(n);
|
||||||
|
double err_norm = fabs(s_norm - pi2_over_6);
|
||||||
|
double err_kahan = fabs(s_kahan - pi2_over_6);
|
||||||
|
|
||||||
|
cout.setf(ios::fixed);
|
||||||
|
cout.precision(10);
|
||||||
|
cout << "\n--- n = " << n << " ---" << endl;
|
||||||
|
cout << "Normal summation: " << s_norm << endl;
|
||||||
|
cout << "Normal error: " << err_norm << endl;
|
||||||
|
cout << "Kahan summation: " << s_kahan << endl;
|
||||||
|
cout << "Kahan error: " << err_kahan << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue