龙格现象.cpp

来自「利用C语言编写的一些常见的差值程序」· C++ 代码 · 共 53 行

CPP
53
字号
#include<stdio.h>
#define MAX_N 100
typedef struct tagPOINT
{double x;
 double y;
}POINT;

int main(){
	double n;
    int i,j;
   POINT points[MAX_N+1];
   double x=0,h,temp,newton; 
   double diff[MAX_N+1];
   printf("\nInput n value:");
   scanf("%lf",&n);
   if(n>MAX_N)
   {
	   printf("The input %d is larger than %d,please redefine the %d.\n",n,MAX_N,MAX_N);
	   return 1;
   }
   if(n<=0)
   {
	   printf("Please input a number between 1 and %d.\n",MAX_N);
	   return 1;
   }
   h=2/n;
  
   for(i=0;i<=n;i++)
   { points[i].x=-1+i*h;
   points[i].y=1/(1+25*points[i].x*points[i].x);
   }
   printf("Now input the x value:");
   while(x!=0){
   scanf("%lf",&x);
   for(i=0;i<=n;i++) diff[i]=points[i].y;
   for(i=0;i<n;i++)
   {for(j=n;j>i;j--)
   { 
	   diff[j]=(diff[j]-diff[j-1])/(points[j].x-points[j-i-1].x);
   }
   }
   temp=1;newton=diff[0];
   for(i=0;i<n;i++)
   {
	   temp=temp*(x-points[i].x);
	   newton=newton+temp*diff[i+1];
   }
   printf("newton(%f)=%f\n",x,newton);
   }
   return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?