Implementation of Newton Method written in C++.

```IN
-3
0.0000001
OUT
X: -3 f(x): 2
X: -2.5 f(x): 0.25
X: -2.41667 f(x): 0.00694444
X: -2.41422 f(x): 6.0073e-06
```
```// ? 2018 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

#include <iostream>
#include <math.h>

using namespace std;
static double function(double x);
static double functionDerivative(double x);

int main() {
double prevX;
double x;
double precision;

cout << "Enter initial guess: ";
cin >> x;

prevX = x;

cout << "Enter precision of method: ";
cin >> precision;

while (abs(function(x)) > precision) {
cout << "X: " << x << " f(x): " << function(x) << endl;

x = prevX - (function(prevX) / functionDerivative(prevX));
prevX = x;
}

int a;
cin >> a; //Wait before exiting

return 0;
}

static double function(double x) //x^2 + 2x -1
{
return x * (x + 2) - 1;
}

static double functionDerivative(double x)
{
return 2 * x + 2;
}```

C++ Newton Method
Tagged on:

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close