2016-04-03 8 views
0

Brauchen Sie etwas Hilfe mit diesem Code. Ich habe versucht, zu finden, wenn der Code einen Fehler hat, weil die approximierte Lösung von cos x - x-1.57 statt 0.739 ist. DankeFixpunkt Iteration in Dev C++ Probleme

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

Danke für Ihre Hilfe!

+0

die numerische Methode, die Sie implementieren und in der Nähe eines Punktes für die Wurzel suchen? –

+0

Ich versuchte mit p0 = 1 – Alexei0709

+0

Scheint, wie ich das If (i> N) innerhalb der Weile beseitigen muss, richtig? – Alexei0709

Antwort

1

Die Methode der einfachen Iterationen ist die Substitution x = F (x). Für Ihre Gleichung 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; 
}