2019年3月15日 星期五

C語言 例題1-5 利用Lagrange 已知下列數據 求 xa=1.5 , 2.5 ,3.5 的值並計算誤差值=?

C語言 例題1-5 利用Lagrange 已知下列數據 求 xa=1.5 , 2.5  ,3.5  的值並計算誤差值=?   P(x) ,  f(x)=ln(x)

xa=1.5
xa=2.5
xa=3.5

x       f(x)
=========
1.0     0.0
2.0     0.693
3.0     1.099
4.0     1.386
=========

程式

/* 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 <conio.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,log(xb));
        printf("The value of | p(%.4lf)-f(%.4lf)|=%.6lf\n",xb,xb, (log(xb)-ff) );
   }
   return 0;
}

輸入資料
input text (sdtin)
n=3 n1=2
1.0  0.0
2.0  0.693
3.0  1.099
4.0  1.386
1.5
2.5
3.5

輸出資料
The value of p(1.5000)=0.3929
The value of f(1.5000)=0.4055
The value of | p(1.5000)-f(1.5000)|=0.012590
The value of p(2.5000)=0.9214
The value of f(2.5000)=0.9163
The value of | p(2.5000)-f(2.5000)|=-0.005084
The value of p(3.5000)=1.2469
The value of f(3.5000)=1.2528
The value of | p(3.5000)-f(3.5000)|=0.005888




沒有留言:

張貼留言

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

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