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]$.
- #include <stdio.h>
 - #include <stdlib.h>
 - #include <math.h> /**/
 - float f(float x);
 - int sig(float v);
 - int main(void)
 - {
 - int i=0,N=100;
 - float a=0.0,b=1.0,p=(a+b)/2,FA=0.0,FP=0.0;
 - float TOL=0.00001;
 - printf("n an bn pn f(pn)\n");
 - /*Step1*/
 - i=1;
 - FA=f(a);
 - /*Step2*/
 - while(i<=N)
 - { /*Step3*/
 - p=a+(b-a)/2;
 - FP=f(p);
 - printf("%2d %.9f %.9f %.9f %+.9f\n",i,a,b,p,f(p));
 - /*Step4*/
 - if(FP==0 || (b-a)/2<TOL)
 - {printf("n=%d, p=%+f\n",i,p);break;}
 - /*Step5*/
 - i=i+1;
 - /*Step6*/
 - if(sig(FA)*sig(FP)>0){a=p;FA=FP;}
 - else b=p;
 - }
 - printf("method failed after N=%d iterations.",N);
 - system("PAUSE");
 - return 0;
 - }
 - float f(float x)
 - {
 - return sqrt(x)-cos(x);
 - }
 - int sig(float u)
 - {
 - if(u>0){return 1;}
 - else if(u<0){return -1;}
 - else {return 0;}
 - }
 
c語言執行結果:
沒有留言:
張貼留言