定点迭代
我试图找到这样的 p,对于给定的函数 f(p),我们有等式
p=f(p); 这是
#include <iostream>
#include<math.h>
using namespace std;
float fixed(float x){
return (float)(pow(x,3)-4*pow(x,2)-10);
}
int main(){
float p=0.0;
float p0=1.5;
float tol=(float).001;
int N=25;
int i=1;
while(i<N){
p=(float)fixed(p0);
if((p-p0)<tol){
cout<<p<<endl;
break;
}
i=i+1;
p0=p;
if(i>N){
cout<<"solution not found ";
break;
}
}
return 0;
}
我尝试过不同初始点的代码,也尝试了不同的容差,但结果非常无意义-16或-15。有些东西,那么出了什么问题?代码正确吗?请帮助
i am trying to find such p,that for given function f(p),we have equality
p=f(p);
here is code
#include <iostream>
#include<math.h>
using namespace std;
float fixed(float x){
return (float)(pow(x,3)-4*pow(x,2)-10);
}
int main(){
float p=0.0;
float p0=1.5;
float tol=(float).001;
int N=25;
int i=1;
while(i<N){
p=(float)fixed(p0);
if((p-p0)<tol){
cout<<p<<endl;
break;
}
i=i+1;
p0=p;
if(i>N){
cout<<"solution not found ";
break;
}
}
return 0;
}
i have tried different initial point,also different tolerance,but result is very nonsense -16 or -15.something,so what is wrong?is code correct?please help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你根本不存在迭代算法适用的情况。 请参阅此处了解某些条件。您的函数在 1.5 附近没有有吸引力的固定点,并且算法发散。
但为什么是数字:您的函数是
f(x) = x^3 - 4x - 10
,因此求解f(x) = x
相当于找到f(x) = x
的零点code>f(x) - x,并且在 5.35 附近只有一个实数零。然而,此时的f'(x)
非常大,因此即使在那里,迭代算法也无法使用。数值求根算法可能是更合适的方法。
I think you simply don't have a situation in which the iterative algorithm is applicable. See here for some conditions. Your function doesn't have an attractive fixed point near 1.5, and the algorithm diverges.
But why the numerics: Your function is
f(x) = x^3 - 4x - 10
, so solvingf(x) = x
amounts to finding the zeros off(x) - x
, and there is only one real zero near 5.35. Howevever,f'(x)
at that point is very large, so even there the iterative algorithm isn't usable.A numeric root-finding algorithm may be a more appropriate approach.
我不确定你想要实现什么,但可能使用 :
而不是 :
会让你更接近你想要去的地方。
原因是所有负值都小于
.001
,因此如果函数的结果是负值(如本例所示),您将立即停止。顺便说一句:这个检查:
永远不会是真的。您可能想使用
==
或>=
而不是>
。I'm not sure what you're trying to achieve, but probably using :
instead of :
will get you closer to where you want to go.
The reason is that all negative values are smaller than
.001
, so if the result of the function is a negative value (like in this case), you'll stop immediately.Btw : this check :
will never be true. You probably meant to use
==
or>=
instead of>
.是等值的正确公式。如果是特殊范围,您还必须注意 NaN 和 Inf。
Is the correct formula for equal values. In case of special ranges you also have to care for NaN and Inf.