Skip to content

Instantly share code, notes, and snippets.

@markusbuchholz
Created June 21, 2021 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markusbuchholz/d20fdaec9c1e5d48c19e1c0b904d4e16 to your computer and use it in GitHub Desktop.
Save markusbuchholz/d20fdaec9c1e5d48c19e1c0b904d4e16 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <cmath>
#include <iomanip> // std::setprecision
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
//-----------------------------------------------------------
std::vector<double> generateLinspaceDiff(std::vector<double> vec, double start, double stop)
{
std::vector<double> linspace;
int size = vec.size();
double h = (stop - start) / size;
for (int ii = 0; ii < size; ii++)
{
linspace.push_back(start + h * ii);
}
std::cout << "size: " << size << std::endl;
std::cout << "linspace: " << linspace.size() << std::endl;
return linspace;
}
//-----------------------------------------------------------
double function(double xx)
{
return std::sqrt(1 - xx * xx);
}
//-----------------------------------------------------------
void plotDiff(std::vector<double> yy, double start, double stop)
{
plt::figure_size(1200, 780);
std::vector<double> xx = generateLinspaceDiff(yy, start, stop);
plt::plot(xx, yy);
plt::title("Numerical Differentiation");
plt::named_plot("Newton method", xx, yy);
plt::legend();
plt::show();
}
//-----------------------------------------------------------
double functionDiff(double xx)
{
return xx * xx * xx;
}
std::vector<double> differentiationNewton(double (*functionDiff)(double), double aa, double bb, int n)
{
double h = (bb - aa) / n;
std::vector<double> output;
for (int ii = 0; ii < n; ii++)
{
double check = (functionDiff((bb * ii) / h + aa + h) - functionDiff((bb * ii) / h + aa)) / n;
output.push_back((functionDiff((bb * ii) / h + aa + h) - functionDiff((bb * ii) / h + aa)) / n);
std::cout << " => " << check << std::endl;
}
return output;
}
//-----------------------------------------------------------
int main()
{
std::vector<double> output3 = differentiationNewton(functionDiff, -2.0, 2.0, 10000);
plotDiff(output3, -2.0, 2.0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment