2013年4月11日 星期四

2.1 the besection method 習題組 2.1 NO.1

Numerical Analysis數值分析筆記 / 

2.1 The Bisection Method /

習題組 2.1 /



NO.1.
use the bisetion method to find the $p_3$ for $f(x)=\sqrt{x}-\cos x $ on $[0,1]$.


2.1 NO.01


C 程式語言:

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

    c語言執行結果:

     2.1  BisectionNO.1

    沒有留言:

    張貼留言