2019年3月16日 星期六

C語言 習題1-1-b請用Lanrange內差法寫出下列諸點的方程式

C語言 習題1-1-b請用Lanrange內差法寫出下列諸點的方程式

x       f(x)
============
-2.0   0.00
-1.0   4.00
0.0    0.00
1.0   -6.00
2.0   -8.00
============

並計算 P[-2.5 , -2.2 ,-1.5 , 0.5 , 1.5 , 2.2] 之值並與 f(x)=x^3-x^2 -6 x 的誤差


程式
/* ex1-4.c: Lagrange Interpolation Algorithm
 * Read in data file of ex1-4.dat which has n point values
 * and the value of interpolating point xa. Based on Lagrange
 * Interpolation algorithm to compute p(xa) and output its value.
 * (x[i],f[i]):given points and n+1 are number of points
 * Ln,k(x)=l=summation of (x-x[i])/(x[k]-x[i]).
 * p(x)=ff=L(x)*f(x[k])
 */
#include <stdio.h>
#include <math.h>

int main()
{
   double x[30],f[30],l,ff,xa[30],xb;
   int i,k,n ,n1 ,j ;
 
   scanf("n=%d n1=%d",&n,&n1);
   getch();
 
   for(k=0;k<=n;k++)
   {
      scanf("%lf %lf",&x[k],&f[k]);
      getch();
   }
 
   for(k=0;k<=n1;k++)
   {
      scanf("%lf",&xa[k]);
      getch();
      //printf("The value of p(%.4lf)\n",xa[k]);
   }
 
   for (j=0;j<=n1;j++)
   {
        xb=xa[j];
        //printf("The value of p(%.4lf)\n",xb);
        ff=0.0;
        for(k=0;k<=n;k++)
        {
            l=1.0;
            for(i=0;i<=n;i++)
            {
           if(i !=k)
           {
              l=l*(xb-x[i])/(x[k]-x[i]);
               getch();
           }
            }
        ff=ff+l*f[k];
        }
        printf("The value of p(%.4lf)=%.4lf\n",xb,ff);
        printf("The value of f(%.4lf)=%.4lf\n",xb,(pow(xb,3)-xb*xb-6*xb));
        printf("The value of | p(%.4lf)-f(%.4lf)|=%.6lf\n",xb,xb, ((pow(xb,3)-xb*xb-6*xb)-ff) );
   }
   return 0;
}


輸入資料
n=4 n1=5
-2.0 0.0
-1.0 4.0
0.0  0.0
1.0  -6.0
2.0  -8.0
-2.5
-2.2
-1.5
0.5
1.5
2.2

輸出畫面
The value of p(-2.5000)=-6.8750
The value of f(-2.5000)=-6.8750
The value of | p(-2.5000)-f(-2.5000)|=0.000000
The value of p(-2.2000)=-2.2880
The value of f(-2.2000)=-2.2880
The value of | p(-2.2000)-f(-2.2000)|=0.000000
The value of p(-1.5000)=3.3750
The value of f(-1.5000)=3.3750
The value of | p(-1.5000)-f(-1.5000)|=0.000000
The value of p(0.5000)=-3.1250
The value of f(0.5000)=-3.1250
The value of | p(0.5000)-f(0.5000)|=0.000000
The value of p(1.5000)=-7.8750
The value of f(1.5000)=-7.8750
The value of | p(1.5000)-f(1.5000)|=0.000000
The value of p(2.2000)=-7.3920
The value of f(2.2000)=-7.3920
The value of | p(2.2000)-f(2.2000)|=0.000000

沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...