Created
June 21, 2021 19:53
-
-
Save markusbuchholz/61645f657adfeb38025d0c69468172f0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <cmath> | |
#include <iomanip> // std::setprecision | |
#include "matplotlibcpp.h" | |
namespace plt = matplotlibcpp; | |
//----------------------------------------------------------- | |
std::vector<int> generateLinspace(std::vector<double> vec) | |
{ | |
std::vector<int> linspace; | |
int size = vec.size(); | |
for (int ii = 0; ii < size; ii++) | |
{ | |
linspace.push_back(ii); | |
} | |
return linspace; | |
} | |
//----------------------------------------------------------- | |
double function(double xx) | |
{ | |
return std::sqrt(1 - xx * xx); | |
} | |
//----------------------------------------------------------- | |
std::vector<double> rectangleMethod(double (*function)(double), double aa, double bb, int n) | |
{ | |
std::vector<double> output; | |
double sum{0}; | |
double h = (bb - aa) / n; | |
for (int ii = 0; ii < n; ii++) | |
{ | |
sum += function(aa + (ii + 0.5) * h); | |
output.push_back(2 * sum * h); | |
} | |
return output; | |
} | |
//----------------------------------------------------------- | |
std::vector<double> trapezoidalMethod(double (*function)(double), double aa, double bb, int n) | |
{ | |
std::vector<double> output; | |
double h = (bb - aa) / n; | |
double aA = function(aa) * 0.5; | |
double bB = function(bb) * 0.5; | |
double sum{0}; | |
for (int ii = 1; ii < n; ii++) | |
{ | |
sum += function(aa + ii * h); | |
output.push_back(2 * h * (aA + bB + sum)); | |
} | |
return output; | |
} | |
//----------------------------------------------------------- | |
void plot(std::vector<double> yy) | |
{ | |
plt::figure_size(1200, 780); | |
std::vector<int> xx = generateLinspace(yy); | |
plt::plot(xx, yy); | |
plt::title("Numerical Integration"); | |
plt::named_plot("trapezoid method", xx, yy, "b-"); | |
plt::legend(); | |
plt::show(); | |
} | |
//----------------------------------------------------------- | |
int main() | |
{ | |
std::vector<double> output1; | |
std::vector<double> output2; | |
output1 = rectangleMethod(function, -1, 1, 100000); | |
output2 = trapezoidalMethod(function, -1, 1, 100000); | |
//rectangle Method | |
// for (auto &i : output1) | |
// { | |
// std::cout << std::setprecision(10) << " ==> " << i << std::endl; | |
// } | |
// plot(output1); | |
// trapezoidal Method | |
for (auto &i : output2) | |
{ | |
std::cout << std::setprecision(10) << " ==> " << i << std::endl; | |
} | |
plot(output2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment