Dev C++问题中的不动点迭代
Fixed point iteration in Dev C++ problems
需要一些有关此代码的帮助。我一直在试图找出代码是否有错误,因为cos x - x
的近似解是-1.57
,而不是0.739
。感谢
double f(double x)
{
double y;
y = cos(x) - x;
return y;
}
int main()
{
double p,p0;
int i=1,N;
cout<<"p0 = ";
cin>>p0;
cout<<"N = ";
cin>>N;
while(i <= N)
{
p = f(p0);
if(fabs(p-p0) < eps)
{
cout<<p<<endl;
break;
}
cout<<"Iteration "<<i<<": p = "<<p<<endl;
i++;
p0 = p;
cout<<"The solution is "<<p<<endl;
if(i>N)
{
cout<<"Solution not found (method diverges)"<<endl;;
break;
}
}
cout<<"The approximated solution is x = "<<p<<" in the iteration "<<i-1<<endl;
system("PAUSE");
return 0;
}
谢谢你的帮助!
简单迭代的方法是替换x=F(x)。对于方程x=cos(x)。
Ideone
#include <iostream>
#include <cmath>
using namespace std;
double f(double x)
{
return cos(x);
}
int main()
{
double p,p0=1,eps = 0.001;
int i=1,N=1000;
while(i <= N)
{
p = f(p0);
if(fabs(p-p0) < eps)
{
cout<<p<<endl;
break;
}
cout<<"Iteration "<<i<<": p = "<<p<<endl;
i++;
p0 = p;
cout<<"The solution is "<<p<<endl;
if(i>N)
{
cout<<"Solution not found (method diverges)"<<endl;;
break;
}
}
cout<<"The approximated solution is x = "<<p<<" in the iteration "<<i-1<<endl;
return 0;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 在向量内的向量上迭代
- 为什么output_editor Concept不需要output_e迭代器标记
- TSP递归解的迭代形式
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器