2018年12月28日 星期五

使用Newton-Raphson理則解 cos(x) - x =0 非線性方程式解

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




==========================
ONLINE C語言
https://www.onlinegdb.com/online_python_compiler#
==========================
/* ex2-4.c is used for solving nonlinear equation f(x)=0
 * based on Newton-Raphson Method with initial approximation
 * p0.
 */
#include <stdio.h>
#include <math.h>
#define MAX  100
#define TOL  0.001
#define PI   3.14159
#define  f(x)   (cos(x)-x)
#define  ff(x)  (-sin(x)-1)
void main()
{
  int i=1;
  double x0,x;
  x0=1.0;
  while(i<=MAX)
  {
     x=x0-f(x0)/ff(x0);
     printf("%2d   %10.7lf\n",i-1,x0);
     if(fabs(x-x0) <TOL)
     {
printf("Root=%10.7lf x-x0=%10.7lf\n",x,fabs(x-x0));
exit(0);
     }
     i++;
     x0=x;
  }
  printf("Newton-Raphson Method failed after %2d \
  iterations!!!\n",i);
  return;
}

===============
DEV c++  C語言模式下
===============
/* ex2-4.c is used for solving nonlinear equation f(x)=0
 * based on Newton-Raphson Method with initial approximation
 * p0.
 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX  100
#define TOL  0.001
#define PI   3.14159
#define  f(x)   (cos(x)-x)
#define  ff(x)  (-sin(x)-1)


/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

  int i=1;
  double x0,x;
  x0=1.0;
  while(i<=MAX)
  {
     x=x0-f(x0)/ff(x0);
     printf("%2d   %10.7lf\n",i-1,x0);
     if(fabs(x-x0) <TOL)
     {
printf("Root=%10.7lf x-x0=%10.7lf\n",x,fabs(x-x0));
exit(0);
     }
     i++;
     x0=x;
  }
  printf("Newton-Raphson Method failed after %2d \
  iterations!!!\n",i);
  return 0;
}

沒有留言:

張貼留言

2024產專班 作業2

 2024產專班 作業2   1. 系統圖       ESP32+MFRC522 組成RFID Reader 可以將RFID卡片的UID 透過 MQTT協定    上傳(發行 主題 (:topic) alex9ufo/2024/RFID/RFID_UID  ,, Payload...