2019年1月17日 星期四

利用Lagrange內插法滿足 f(x)=log e (x)=ln (x) -----(a)

利用Lagrange內插法滿足 f(x)=log e (x)=ln (x)
'''===========================================
n=3
xa=1.5
1.0  0.0
2.0  0.693
3.0  1.099
4.0  1.386

===========================================
/* 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])
 */
==========================================='''
print('\nLagrange Interpolation Algorithm\n')

xa=1.5
x= list()
x.extend([1.0,2.0,3.0,4.0])
f= list()
f.extend([0.0,0.693,1.099,1.386])
result=0.0
n=3

print(x)
print(f)
print('\n')

for k in range (0,n+1):    #n -->n+1
    temp=1.0;
    for i in range (0,n+1):  #n -->n+1
        if(i !=k):
            temp=temp * ( xa - x[i]) / ( x[k] - x[i])
    result=result+temp*f[k]

s = 'The value of p' + repr(xa) + '= ' + repr(result) + '...'
print(s)



輸出結果

Lagrange Interpolation Algorithm

[1.0, 2.0, 3.0, 4.0]
[0.0, 0.693, 1.099, 1.386]


The value of p1.5= 0.392875...
>>> 


原來C語言
'''==============================================
/* 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>
int main()
{
   double x[30],f[30],l,ff,xa;
   int i,k,n;
   scanf("n=%d xa=%lf",&n,&xa);
    getch();
   for(k=0;k<=n;k++)
   {
      scanf("%lf %lf",&x[k],&f[k]);
      getch();
   }
   ff=0.0;
   for(k=0;k<=n;k++)
   {
      l=1.0;
      for(i=0;i<=n;i++)
      {
 if(i !=k)
 {
    l=l*(xa-x[i])/(x[k]-x[i]);
     getch();
 }
      }
      ff=ff+l*f[k];
   }
   printf("The value of p(%.4lf)=%.4lf\n",xa,ff);
   return 0;
}

=============================================='''

沒有留言:

張貼留言

Messaging API作為替代方案

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