2019年3月26日 星期二

C語言 例題2-7 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根

C語言 例題2-6 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根

C語言 例題2-7 已知方程式 e^x + x^-2 + 2 cosx -6 利用正割法 找出f(x)=0的根


/* ex2-7.c Secant Method is similar to Newton-Raphson
 *  Method used for find solutions to f(x)=0 given
 *  initial approximations x0 and x1.
 */
#include <stdio.h>
#include <math.h>
#define  MAX  50
#define  PI  3.14159
#define  TOL  0.00001
#define  f(x)   (exp(x)+1/pow(2,x)+2*cos(x)-6)
void main()
{
   int i=2;
   double x0,x1,x,q0,q1;
   x0=1.8;
   x1=2.0;
   q0=f(x0);
   q1=f(x1);
   printf("i       xi           f(x)\n");
   printf("%-2d   %10.6lf   %10.6lf\n",0,x0,q0);
   printf("%-2d   %10.6lf   %10.6lf\n",1,x1,q1);
   while(i<=MAX)
   {
      x=x1-q1*(x1-x0)/(q1-q0);
      printf("%-2d   %10.6lf   %10.6lf\n",i,x,f(x));
      if(fabs(x-x1) < TOL)
      {
    printf("The Root=%10.6lf f(%10.6lf)=%10.6lf\n",x,x,f(x));
    exit(0);
      }
      else
      {
    i++;
    x0=x1;
    q0=q1;
    x1=x;
    q1=f(x);
      }
   }
   if(i>MAX)
     printf("Secant Method faileds!!!\n");
   return;
}


輸出畫面

i       xi           f(x)                                                                                                                      
0      1.800000    -0.117582                                                                                                                   
1      2.000000     0.806762                                                                                                                   
2      1.825441    -0.016116                                                                                                                   
3      1.828860    -0.002147                                                                                                                   
4      1.829385     0.000007                                                                                                                   
5      1.829384    -0.000000                                                                                                                   

The Root=  1.829384 f(  1.829384)= -0.000000  

沒有留言:

張貼留言

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

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