2018年12月29日 星期六

例題 EX2-8 定點回路法 求非線性方程式 f(x)=e^x - 3x^2 = 0 C語言

定點回路法 求非線性方程式 f(x)=e^x - 3x^2 = 0 C語言



聯立方程式   y=x
                       y=(e^x/3) ^ 0.5

/* ex2-8.c is used for solving nonlinear equation
 * based on Fixed-Point Algorithm g(x)=x with initial
 * approximation P0.
 */
#include <stdio.h>
#include <math.h>
#define MAX  50
#define TOL 0.0001
#define  g(x)  pow( (exp(x)/3) , 0.5) 
void main()
{
   int i=1;
   double x0,x;
   x0=0.0;
   while(i<=MAX)
   {
      x=g(x0);
      printf("%-2d  %10.7lf\n",i-1,x0);
      if(fabs(x-x0) < TOL)
      {
printf("The Root=%10.7lf  x-x0=%10.7lf\n",x,fabs(x-x0));
exit(0);
      }
      i++;
      x0=x;
   }
   printf("Fixed-point failed after %d iteration.\n",i);
   return;
}
======================
輸出結果
======================
0    0.0000000
1    0.5773503
2    0.7705652
3    0.8487220
4    0.8825453
5    0.8975975
6    0.9043784
7    0.9074499
8    0.9088446
9    0.9094786
10   0.9097669
11   0.9098981
The Root= 0.9099578  x-x0= 0.0000597


聯立方程式   y=x
                       y=-(e^x/3) ^ 0.5



/* ex2-8.c is used for solving nonlinear equation
 * based on Fixed-Point Algorithm g(x)=x with initial
 * approximation P0.
 */
#include <stdio.h>
#include <math.h>
#define MAX  50
#define TOL 0.0001
#define  g(x)  - pow( (exp(x)/3) , 0.5) 
void main()
{
   int i=1;
   double x0,x;
   x0=0.0;
   while(i<=MAX)
   {
      x=g(x0);
      printf("%-2d  %10.7lf\n",i-1,x0);
      if(fabs(x-x0) < TOL)
      {
printf("The Root=%10.7lf  x-x0=%10.7lf\n",x,fabs(x-x0));
exit(0);
      }
      i++;
      x0=x;
   }
   printf("Fixed-point failed after %d iteration.\n",i);
   return;
}
======================
輸出結果
======================
0    0.0000000
1   -0.5773503
2   -0.4325829
3   -0.4650559
4   -0.4575660
5   -0.4592828
6   -0.4588887
The Root=-0.4589791  x-x0= 0.0000904

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...