牛顿方法实现 [英] newtons methods implementation
问题描述
#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>
几种情况:
- 2
- 您需要确保您的出发点实际上是收敛的。
- 注意破坏性取消在
导出
函数。
要展开最后一个点,一般的方法是减少 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:
- 2 iterations is rarely going to be enough even in the best case.
- You need to make sure your starting point is actually convergent.
- 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屋!