2019年3月17日 星期日

C語言例題 2-1 解 f(x)=x^3 -4x +2 =0 非線性方程式的解

C語言例題 2-1 解 f(x)=x^3 -4x +2 =0 非線性方程式的解

a) f(x)=0 在(2,3) 與(1.5,1.8)是否有解
b) 測試a=0.0 , b=2.0 之間有多少根root 存在


程式
// C program for implementation of Bisection Method for 
// solving equations 
#include <stdio.h>
#define EPSILON 0.01 
  
// An example function whose solution is determined using 
// Bisection Method. The function is x^3 - 4x  + 2 
double func(double x) 
{ 
    return x*x*x - 4*x + 2; 
} 
  
// Prints root of func(x) with error of EPSILON 
void bisection(double a, double b) 
{ 
    if (func(a) * func(b) >= 0) 
    { 
        printf("You have not assumed right a and b\n"); 
        return; 
    } 
  
    double c = a; 
    while ((b-a) >= EPSILON) 
    { 
        // Find middle point 
        c = (a+b)/2; 
  
        // Check if middle point is root 
        if (func(c) == 0.0) 
            break; 
  
        // Decide the side to repeat the steps 
        else if (func(c)*func(a) < 0) 
            b = c; 
        else
            a = c; 
    } 
    printf("The value of root is :%.4lf\n" ,c); 
} 
  
// Driver program to test above function 
int main() 
{ 
    // Initial values assumed 
    double a =0.0, b =2.0 , x=a;
    while ((b-x) >= -0.1)
    {
        printf("%0.1lf <---> %0.4lf\n",x,func(x));
        x=x+0.1;
    }
    
    a =2.0;
    b =3.0 ;
    printf("\n%0.1lf to %0.1lf , the roots --> \n",a,b);
    bisection(a, b); 
    
    a =1.5;
    b =1.8 ;
    printf("\n%0.1lf to %0.1lf , the roots --> \n",a,b);
    bisection(a, b);   
    
    return 0; 
} 
輸出畫面
0.0 <---> 2.0000
0.1 <---> 1.6010
0.2 <---> 1.2080
0.3 <---> 0.8270
0.4 <---> 0.4640
0.5 <---> 0.1250
0.6 <---> -0.1840
0.7 <---> -0.4570
0.8 <---> -0.6880
0.9 <---> -0.8710
1.0 <---> -1.0000
1.1 <---> -1.0690
1.2 <---> -1.0720
1.3 <---> -1.0030
1.4 <---> -0.8560
1.5 <---> -0.6250
1.6 <---> -0.3040
1.7 <---> 0.1130
1.8 <---> 0.6320
1.9 <---> 1.2590
2.0 <---> 2.0000

2.0 to 3.0 , the roots --> 
You have not assumed right a and b

1.5 to 1.8 , the roots --> 
The value of root is :1.6781


f(x)在(2,3)之間 無根存在
int main() 
{ 
    // Initial values assumed 
    double a =2, b = 3; 
    bisection(a, b); 
    return 0; 
} 
You have not assumed right a and b
f(x)在(1.5,1.8)之間 有根 = 1.6781
int main() 
{ 
    // Initial values assumed 
    double a =1.5, b =1.8; 
    bisection(a, b); 
    return 0; 
} 
The value of root is :1.6781

沒有留言:

張貼留言

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

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