开发者

newtons methods implementation

i have posted a few hours ago question about newtons method,i got answers and want to thanks everybody,now i have tried to 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){
            co开发者_如何学Gout<<p<<endl;
            break;

        }


        i=i+1;
        p0=p;


    if (i>=N){
        cout<<"solution not found "<<endl;
        break;
    }
    }



    return 0;
}

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


Several things:

  1. 2 iterations is rarely going to be enough even in the best case.
  2. You need to make sure your starting point is actually convergent.
  3. Be aware of destructive cancellation in your derivative function. You are subtracting two numbers that are very close to each other so the difference will lose a lot of precision.

To expand on the last point, the general method is to decrease h as the value converges. But as I mentioned in your previous question, this "adjusting" h method essentially (algebraically) reduces to the Secant Method.


If you make h too small then your derivative will be innaccurate due to floating point roundoff. Your code would benefit from using double precision rather than single, especially as you are doing differentiation by finite difference. With double precision your value of h would be fine. If you stick to single precision you will need to use a larger value.

Only allowing 2 iterations seems rather restrictive. Make N larger and get your program to print out the number of iterations used.

Also, no need to use pow. Simply write 1e-7.


You're only allowing 2 iterations which may not be enough to get close enough to the answer. If you only have 1 correct bit to start, you can expect to have at best about 4 good bits after 2 iterations. You're looking for 10 bits accuracy (0.001 is roughly 1/2^10), you have to allow at least 2 more iterations.

Moreover, the quadratic convergence property only holds when you're close to the solution. When you're further out, it may take longer to get close to the solution.

The optimal h for computing the numerical derivative using central differences is 0.005 * max(1,|x|) for single-precision (float), where |x| is the absolute value of the argument, x. For double precision, it's about 5e-6 * max(1,|x|).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜