2016-04-03 15 views
0

このコードの助けが必要です。 cos x - xの近似解ではなく0.739で、-1.57あるので、私は、コードはいくつかの誤りがある場合に見つけようとしてきました。ありがとうDev C++問題の固定小数点の反復

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

ありがとうございました!

+0

? –

+0

私はp0 = 1で試しました – Alexei0709

+0

私はif(i> N)を中に入れなければならないようですね、そうですか? – Alexei0709

答えて

1

単純反復の方法は、置換、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; 
}