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.                                                                                                                                                                     
                                  

沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...