-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumerical_integration.cc
More file actions
executable file
·81 lines (72 loc) · 1.96 KB
/
Copy pathnumerical_integration.cc
File metadata and controls
executable file
·81 lines (72 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//C++ STD
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
//returns value of the function being integrated
double f(double x){
// No need to add 0.0, and the total integrated sum starts with 1.0 term
if (x == 0.0 || x == 1.0)return 0.0;
else return pow(x, 10);
}
//trapazoidal method
void trap_int(void){
double a = 0.0;
double b = 1.0;
double exact_sum = 1.0/11.0;
ofstream fs;
fs.open("/dataFiles/a.dat");
int n_max = 10000;
fs.precision(20);
//loop over possible values of N
for(int n=10; n<=n_max; n+=100){
//start with the (1/2)*f_n term
double sum = .5;
double N = double(n);
double h = b/N;
//Loop for actual sum
for (int i = 0; i <= N; i++){
double I = double(i);
// h = 1/N, so I*h = a step between 0.0 and 1.0
sum += f(I*h);
}
//factor in h
sum *=h;
// write to file with abs(error)
fs << n << '\t' << sum << '\t' << sqrt((sum - exact_sum)*(sum - exact_sum))/exact_sum << endl;
}
fs.close();
}
//simpson's method (redundent comments omitted)
void simp_int(void){
double a = 0.0;
double b = 1.0;
double exact_sum = 1.0/11.0;
ofstream fs;
fs.open("/dataFiles/b.dat");
int n_max = 10000;
fs.precision(16);
for(int n=10; n<=n_max; n+=100) {
double sum = 1.0;
double N = double(n);
double h = b/N;
for (int i = 0; i <= N; i++){
double I = double(i);
// if odd return 4.0*f
if (i%2 != 0) sum += 4.0*f(I*h);
// if even return 2.0*f
else sum += 2.0*f(I*h);
}
// factor in h/3
sum *=h/3.0;
fs << n << '\t' << sum << '\t' << sqrt((sum - exact_sum)*(sum - exact_sum))/exact_sum << endl;
}
fs.close();
}
int main (int argc, char *argv[]){
trap_int();
simp_int();
return 0;
}