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 55 56 57 58 59 60 61
| #include<cmath>
#include<iostream>
using namespace std;
// the maximum number of iterations
const int MAXITER = 100;
// the accepted error
const double error = 0.0001;
// the Euler constant
const double e = 2.718281828459;
// the function F(x)
#define F(x) ( pow(x, 2) )
// the derivative of the function F(x), meaning F`(x)
#define Fd(x) ( 2*x )
int NewtonMethodForEquation(double& x)
{
int n = 1;
while( ( fabs(F(x)) > error ) && ( n <= MAXITER ) )
{
x = x - ( F(x) / Fd(x) );
n++;
}
return n;
}
int main(){
double x;
int n;
cout<<"Newton's method: " << endl << endl;
cout<< "Give the initial approximation: ";
cin >> x;
// now we apply Newton's method
n = NewtonMethodForEquation(x);
if(n > MAXITER)
cout << "In " << MAXITER << " iterations no solution was found!" << endl;
else
cout << "The solution is: " << x << " and it was found in "
<< n << " iterations" << endl;
//cout<<(1+sqrt(5))/2;
return 0;} |
Partager