2011-10-07 70 views
1

我試圖找到這樣的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.something,那麼什麼是錯了嗎?是的代碼是否正確?請幫

回答

3

我認爲你根本沒有一種迭代算法適用的情況。 See here對於某些條件。你的函數在1.5附近沒有一個有吸引力的固定點,算法發散。

但是爲什麼數字:你的函數是f(x) = x^3 - 4x - 10,所以求解f(x) = x等於找到f(x) - x的零,並且在5.35附近只有一個實數零。 Howevever,f'(x)在這一點是非常大的,所以即使那裏的迭代算法是不可用的。

數值找根算法可能是一個更合適的方法。

3

我不知道你想什麼來實現,但可能使用:的

if(fabs(p-p0)<tol){ 

代替:

if((p-p0)<tol){ 

會讓你更接近你想去的地方。

原因是所有的負值都小於.001,所以如果函數的結果是負值(如本例中那樣),您將立即停止。

BTW:此檢查:

if(i>N){ 

永遠不會爲真。您可能打算使用==>=而不是>

+0

uiiiiiiiiiii我忘了它,非常感謝,我會更正它 –

1
fabs(p - p0) <= tol * fabs(p); 

是相等值的正確公式。在特殊範圍的情況下,您還必須關心NaN和Inf。

#include <limits> 
#include <cfloat> 

inline bool Equal(const double& x, const double& y) 
{ 
    const int classX (_fpclass(x)); 

    if(classX != _fpclass(y)) { 
    return false; 
    } 

    switch(classX) { 
     case _FPCLASS_SNAN: 
     case _FPCLASS_QNAN: 
     case _FPCLASS_NINF: 
     case _FPCLASS_NZ : 
     case _FPCLASS_PZ : 
     case _FPCLASS_PINF: 
     return true; 
     break; 
     case _FPCLASS_NN : 
     case _FPCLASS_ND : 
     case _FPCLASS_PD : 
     case _FPCLASS_PN : 
     default: 
     break; 
    } 

    return fabs(x - y) <= std::numeric_limits<double>::epsilon() * fabs(x); 
}