c++ - newtons methods implementation -


i have posted few hours ago question newtons method,i got answers , want everybody,now have tried implement code itself

#include <iostream> #include <math.h> using namespace std; #define h powf(10,-7) #define pi 180 float funct(float x){      return cos(x)-x;   } float derivative (float x){     return (( funct(x+h)-funct(x-h))/(2*h));  } int main(){     float tol=.001;     int n=3;     float p0=pi/4;     float p=0;     int i=1;     while(i<n){          p=p0-(float)funct(p0)/derivative(p0);         if ((p-p0)<tol){             cout<<p<<endl;             break;          }           i=i+1;         p0=p;       if (i>=n){         cout<<"solution not found "<<endl;         break;     }     }        return 0; } 

but writes output "solution not found",in book after 3 iteration when n=3 ,it finds solution .7390851332,so question how small should change h or how should change code such that,get correct answer?

several things:

  1. 2 iterations going enough in best case.
  2. you need make sure starting point convergent.
  3. be aware of destructive cancellation in derivative function. subtracting 2 numbers close each other difference lose lot of precision.

to expand on last point, general method decrease h value converges. mentioned in previous question, "adjusting" h method (algebraically) reduces secant method.


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -