Alexei0709
Alexei0709

Reputation: 113

Fixed point iteration in Dev C++ problems

Need some help with this code. I've been trying to find if the code has some error, because the approximated solution of cos x - x is -1.57, instead of 0.739. Thanks

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;
}

Thanks for your help!

Upvotes: 1

Views: 5296

Answers (1)

user4651282
user4651282

Reputation:

The method of simple iterations is the substitution x = F(x). For your equation 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;
}

Upvotes: 1

Related Questions