2019年3月26日 星期二

C語言 例題2-7已知方程式 e^x + x^-2 + 2 cosx -6 正割法(secant method)

C語言 例題2-7已知方程式 e^x + x^-2 + 2 cosx -6  正割法(secant method)

利用正割法(secant method) 採用誤差0.00001 找出f(x)=0的根 

程式
// C Program to find root of an equations using secant method 
#include <stdio.h>
#include <math.h>


// function takes value of x and returns f(x) 
float f(float x) 
{ 
    // we are taking equation as  e^x + x^-2 + 2 cosx -6
    float f =  exp(x) + (1/pow(x,2)) + 2*cos(x) - 6.0;
    return f; 
} 
  
void secant(float x1, float x2, float E) 
{ 
    float n = 0, xm, x0, c; 
    if (f(x1) * f(x2) < 0)
    { 
        do { 
            // calculate the intermediate value 
            x0 = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1)); 
  
            // check if x0 is root of equation or not 
            c = f(x1) * f(x0); 
  
            // update the value of interval 
            x1 = x2; 
            x2 = x0; 
  
            // update number of iteration 
            n++; 
  
            // if x0 is the root of equation then break the loop 
            if (c == 0) 
                break; 
            xm = (x1 * f(x2) - x2 * f(x1)) / (f(x2) - f(x1));
            printf("xm=%0.5lf\n", xm); 
        
            
        } while (fabs(xm - x0) >= E); // repeat the loop 
                                // until the convergence 
  
        printf("Root of the given equation=%0.5lf", x0); 
        printf("\nNo. of iterations = %0.0lf", n); 
    
        
    } else
        
        printf("Can not find a root in the given inteval"); 
} 
  
// Driver code 
int main() 
{ 
    // initializing the values 
    float x1 = 1.8, x2 = 2.0, E = 0.0001; 
    secant(x1, x2, E); 
    return 0; 
} 

輸出畫面

xm=1.82444                                                                                                                                       
xm=1.82498                                                                                                                                       
xm=1.82498                                                                                                                                       
Root of the given equation=1.82498                                                                                                               
No. of iterations = 3                                                                                                                            
                                                                                                                                                 
...Program finished with exit code 0                                                                                                             
Press ENTER to exit console.      



沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...