-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex22.cpp
More file actions
68 lines (57 loc) · 1.81 KB
/
Copy pathex22.cpp
File metadata and controls
68 lines (57 loc) · 1.81 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
#include <cmath>
#include <iostream>
#include <cstdlib>
#include <cassert>
typedef double (*pfn)(double);
double trapezoidal(double a, double b, pfn f, int n);
double simpson(double a, double b, pfn f, int n);
inline double f(double d) { return exp(-pow(d,2)); }
int main(int argc, char *argv[])
{
using namespace std;
int n =100;
double result = trapezoidal(0, 2, f, n);
cout.precision(10);
cout << "Integral e^(-x^2) using trapezoidal with n = " << n << " is: "
<< result << endl;
result = simpson(0, 2, f, n);
cout.precision(10);
cout << "Integral e^(-x^2) using simpson with n = " << n << " is: "
<< result << endl;
n =300;
result = trapezoidal(0, 2, f, n);
cout.precision(10);
cout << "Integral e^(-x^2) using trapezoidal with n = " << n << " is: "
<< result << endl;
result = simpson(0, 2, f, n);
cout.precision(10);
cout << "Integral e^(-x^2) using simpson with n = " << n << " is: "
<< result << endl;
n =500;
result = trapezoidal(0, 2, f, n);
cout.precision(10);
cout << "Integral e^(-x^2) using trapezoidal with n = " << n << " is: "
<< result << endl;
result = simpson(0, 2, f, n);
cout.precision(10);
cout << "Integral e^(-x^2) using simpson with n = " << n << " is: "
<< result << endl;
}
double trapezoidal(double a, double b, pfn f, int n)
{
double h = (b - a)/n;
double sum = f(a)*0.5;
for(int i = 1; i < n; i++) sum += f(a + i*h);
sum += f(b)*0.5;
return sum*h;
}
double simpson(double a, double b, pfn f, int n)
{
double h = (b - a)/n;
double sum = f(a)*0.5;
for(int i = 1; i < n; i++) sum += f(a + i*h);
sum += f(b)*0.5;
double summid = 0;
for(int i = 1; i <= n; i++) summid += f(a + (i - 0.5)*h);
return (sum + 2*summid)*h/3;
}