Skip to content

Instantly share code, notes, and snippets.

@markusbuchholz
Last active July 11, 2021 22:41
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/cb29b17b126044b7ea870e6f207bd494 to your computer and use it in GitHub Desktop.
Save markusbuchholz/cb29b17b126044b7ea870e6f207bd494 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include<tuple>
#include <math.h>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
// --------------------------------------------------------------
void plotNumericalApproach(std::vector<int> ii, std::vector<double> yy)
{
plt::figure_size(1200, 780);
plt::title("Nonlinear solution");
plt::plot(ii, yy);
//plt::plot(ii, dyy);
plt::show();
}
// --------------------------------------------------------------
double function(double x){
//return (1 / (1+ std::exp(-x))) - 0.5 ;
return 2* std::sin(x) - std::cos(x)* std::cos(x);
//return x*x - 9;
}
// --------------------------------------------------------------
std::tuple<std::vector<int>, std::vector<double>> nonlinearNewton(double (*function)(double), double start, double error, double h ){
double x0 = start;
double fx0 = function(x0);
int i{0};
std::vector <int> iteration;
std::vector<double> result;
while(std::fabs(fx0) > error){
double diff = (function(x0 + h) - fx0)/ h ;
x0 = x0 -fx0/diff;
fx0 = function(x0);
iteration.push_back(i);
result.push_back(x0);
i++;
}
return std::make_tuple(iteration, result);
}
// --------------------------------------------------------------
int main(){
std::tuple<std::vector<int>, std::vector<double>> result = nonlinearNewton(function, 1.0, 0.000001, 0.001);
std::vector<int> iter = std::get<0>(result);
std::vector<double> solution = std::get<1>(result);
plotNumericalApproach (iter, solution);
for (auto &i : solution){
std::cout<< i << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment