2019年3月17日 星期日

C語言例題2-4 使用Newton-Raphson理則解 cos(x) - x =0 非線性方程式解

C語言例題2-4 使用Newton-Raphson理則解 cos(x) - x =0 非線性方程式解
#define EPSILON 0.001  啟動值 x0=1.0 


程式

// C program for implementation of Newton Raphson Method for 
// solving equations 

#include <stdio.h>
#include <math.h>

#define EPSILON 0.001 

// An example function whose solution is determined using 
// Bisection Method. The function is x^3 + 4x^2  - 10 
double func(double x) 
{ 
    return cos(x) -x; 
} 
  
// Derivative of the above function which is 3*x^x + 8*x 
double derivFunc(double x) 
{ 
    return -sin(x) - 1; 
} 
  
// Function to find the root 
void newtonRaphson(double x) 
{ 
    double h = func(x) / derivFunc(x); 
    int i=0;
    while (abs(h) >= EPSILON) 
    { 
        h = func(x)/derivFunc(x); 
   
        // x(i+1) = x(i) - f(x) / f'(x)   
        x = x - h; 
        i+=1;
        if (i>=1000)
           break;
    } 
  
    printf("The value of the root is : %0.7lf ", x); 
} 
  
// Driver program to test above 
int main() 
{ 
    double x0 = 1.0; // Initial values assumed 
    newtonRaphson(x0); 
    return 0; 
} 

The value of the root is : 0.7390851                                                                                                                                                             
                                                                                                                                                                                                 
...Program finished with exit code 0                                                                                                                                                             
Press ENTER to exit console.                                                                                                                                                                     
                                  

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...