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:
- 2 iterations going enough in best case.
- you need make sure starting point convergent.
- 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
Post a Comment