2018年12月29日 星期六

利用2分法 bisection method 解非線性方程式 e^x - 3x^2 =0

利用2分法 bisection method

plot | e^x - 3 x^2

#define  TOL  0.01 /* tolerance */
   a=-0.5;
   b=-0.4;


/* 習題2-1.c Bisection Method is used for solving the
 * nonlinear equation f(x)=0, its root is between a and b
 */
#include <stdio.h>
#include <math.h>
#define  MAX  50    /* maximum iterations */
#define  TOL  0.01 /* tolerance */
#define  f(x)  (exp(x)-3*pow(x,2))
void main()
{
   double x,a,b,p,h;
   int i=1;
   a=-0.5;
   b=-0.4;
   printf(" i    a(i)        b(i)       p(i)       f(p(i))      h(i)\n");
   while(i<=MAX)
   {
      p=(a+b)/2.0;
      h=fabs((b-a)/2.0);
      printf("%2d   %9.6lf   %9.6lf  %9.6lf   %9.6lf   %9.6lf\n",
     i,a,b,p,f(p),h);
      if(fabs(f(p))==0 || h<TOL)
      {
printf("%2d iterations!!!\n",i);
printf(" The Root=%9.6lf  f(%9.6lf)=%9.6lf\n",p,p,f(p));
exit(0);
      }
      else
      {
if(f(a)*f(p) >0)
    a=p;
else if(f(b)*f(p) >0)
    b=p;
i++;
       }
   }
   printf("Bisection Method failed after %d iterations!!!\n",i);
   return;
}


=====================
輸出出畫面
=====================
i    a(i)        b(i)       p(i)       f(p(i))      h(i)
 1   -0.500000   -0.400000  -0.450000    0.030128    0.050000
 2   -0.500000   -0.450000  -0.475000   -0.054990    0.025000
 3   -0.475000   -0.450000  -0.462500   -0.012011    0.012500
 4   -0.462500   -0.450000  -0.456250    0.009163    0.006250
 4 iterations!!!
 The Root=-0.456250  f(-0.456250)= 0.009163







沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...