牛顿方法实现 [英] newtons methods implementation

查看:172
本文介绍了牛顿方法实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

#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(xh))/(2 * h) ;

}
int main(){
float tol = .001;
int N = 3;
float p0 = PI / 4;
float p = 0;
int i = 1;
while(i
p = p0-(float)funct(p0)/ derivative(p0);
if((p-p0) cout <<<<
break;

}


i = i + 1;
p0 = p;


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



return 0;
}

但我写出输出解决方案未找到,在书后三次迭代n = 3,它找到像这样 .7390851332 的解决方案,所以我的问题是我应该更改小h或我应该如何更改我的代码,以便得到正确的答案? / p>

解决方案

几种情况:


  1. 2

  2. 您需要确保您的出发点实际上是收敛的。

  3. 注意破坏性取消在导出函数。

要展开最后一个点,一般的方法是减少 h 作为值收敛。但是正如我在上一个问题中提到的,这个调整 h 方法基本上(代数)减少为割分法。


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){
            cout<<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.

这篇关于牛顿方法实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆