-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrapz_integral.cpp
More file actions
54 lines (44 loc) · 1.27 KB
/
Copy pathtrapz_integral.cpp
File metadata and controls
54 lines (44 loc) · 1.27 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
#include <iostream>
#include <cmath>
#include <fstream>
#include <chrono>
using namespace std;
using namespace std::chrono;
// Function to integrate
double f(double x) {
return exp(-x) * cos(100.0 * x) * sqrt(x*x*x + sin(x*x));
}
int main() {
double a = 0.0;
double b = 100.0;
long N = 100000000L; // points
double h = (b - a) / (N - 1);
double sum = 0.0;
// Start timer
auto start = high_resolution_clock::now();
// Trapezoidal integration
for (long i = 0; i < N; i++) {
double x = a + h * i;
if (i == 0 || i == N-1) {
sum += f(x);
} else {
sum += 2.0 * f(x);
}
}
double integral = h * sum / 2.0;
// Stop timer
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
// Output results
cout.precision(15);
cout << "Integration result: " << integral << endl;
cout << "Execution time: " << duration.count() / 1e6 << " seconds" << endl;
// Export function data for plotting (between 0 and 5)
ofstream outfile("function_data_cpp.dat");
for (int i = 0; i < 1000; i++) {
double x = 0.0 + (5.0 - 0.0) * i / 999.0;
outfile << x << " " << f(x) << endl;
}
outfile.close();
return 0;
}