2013年3月3日 星期日

the bisection method 二分逼近法 例子1

例子 1:
use the bisection method to find $p_3$ for $f(x)=x^3+4x^2-10$ on $[1,2]$.

首先說明其有根:
因為函數 $f$ 在 $[1,2]$ 連續,且 $f(1)f(2)<0$,由 IVT 可知函數 $f$ 在 $[1,2]$ 中有根。

接者尋找 $p_3$ :

1. $a_1=1$, $b_1=2$,  則 $p_1=\frac{1}{2}(1+2)=\frac{3}{2}$.

2. $a_2=1$, $b_2=p_1=\frac{3}{2}$,  則 $p_2=\frac{5}{4}$.

3. $a_3=p_2=\frac{5}{4}$, $b_3=\frac{3}{2}$,  則 $p_3=\frac{1}{2}(\frac{5}{4}+\frac{3}{2})$.
 
000

using c language:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>       /**/
  4. float f(float u);
  5. int sig(float v);
  6. int main(void)
  7.     int i=0,N=10000;
  8.     float a=1.0,b=2.0,p=1.5,FA=0.0,FP=0.0;
  9.     float TOL=0.0000001;
  10.    
  11.     printf("n   an          bn              pn             f(pn)\n");
  12.     /*Step1*/
  13.     i=1;
  14.     FA=f(a);
  15.    
  16.     /*Step2*/
  17.     while(i<=N)
  18.     {    /*Step3*/
  19.          p=a+(b-a)/2;
  20.          FP=f(p);
  21.         
  22.     printf("%2d    %.9f    %.9f    %.9f    %+.9f\n",i,a,b,p,f(p));    
  23.         
  24.          /*Step4*/
  25.          if(FP==0 || (b-a)/2<TOL)
  26.          {printf("n=%d, p=%+f\n",i,p);break;}
  27.         
  28.          /*Step5*/
  29.          i=i+1;
  30.         
  31.          /*Step6*/
  32.          if(sig(FA)*sig(FP)>0){a=p;FA=FP;}
  33.          else b=p;
  34.          }
  35.     printf("method failed after N=%d iterations.",N);
  36.    
  37.  
  38.    
  39. system("PAUSE");
  40. return 0;       
  41.    }
  42.   
  43.   
  44. float f(float u)
  45. {
  46.       return u*u*u+4*u*u-10;
  47.       }
  48.      
  49. int sig(float u)
  50. {   
  51.      if(u>0){return 1;}
  52.      else if(u<0){return -1;}
  53.      else 0; 
  54.      }

其執行結果:

當 $n=3$, 則 $p_3=1.375$.

 
example1

沒有留言:

張貼留言

教學用,若不慎侵犯絕非故意,請留言通知必於第一時間移除,謝謝。