2019年2月12日 星期二

習題1-1-b 利用Lagrange內差法寫出下面諸點的方程式

習題1-1-b 
利用Lagrange內差法寫出下面諸點的方程式

P9x)= a0 + a1x + a2 x^2 + a3 x^3 + a4 x^4 + ......an x^n 

Python程式


'''
n=4
xa=[-2.5 , -2.2 .-1.5  ,0.5 , 1.5 , 2.2 ]

-2.0   0.00
-1.0   4.00
0.0    0.00
1.0   -6.00
2.0   -8.00

/* pr1-1-b.py : 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])
 */
'''
import math

def fx(x):
    return (math.pow(x,3)-math.pow(x,2) -6*x)


print('\nLagrange Interpolation Algorithm\n')

xa=[-2.5 , -2.2 ,-1.5  ,0.5 , 1.5 , 2.2 ]
x=[-2.0 , -1.0 , 0.0 , 1.0 , 2.0 ]
f=[0.0 , 4.0 , 0.0 , -6.0 , -8.0 ]

n=4  # 5 point n=4


print('x=',x)
print('f=',f)
print('xa=',xa)
print('\n')


for m in range (len(xa)):
    indata=xa[m]
    result=0.0
    print("xa=",repr(indata))
    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 * ( indata - x[i]) / ( x[k] - x[i])
        result = result + temp *f[k]

    s1 = 'The value of p' + repr(indata) + '= ' + repr(result) + '   ...'
    print(s1)

    resultfx=fx(indata)
    s1 = 'The value of f(' + repr(indata) + ')= ' + repr(resultfx) + '   ...'
    print(s1)

    s1 = 'The value of  | f(' + repr(indata) + ') -  p' + repr(indata) + ' = ' + repr( abs(resultfx - result) ) + '  ...'
    print(s1)
    print("\n\n")
   




輸出畫面
======== RESTART: H:/2018-09勤益科大數值分析/數值分析/PYTHON/pr1-1-b.py ==========

Lagrange Interpolation Algorithm

x= [-2.0, -1.0, 0.0, 1.0, 2.0]
f= [0.0, 4.0, 0.0, -6.0, -8.0]
xa= [-2.5, -2.2, -1.5, 0.5, 1.5, 2.2]


xa= -2.5
The value of p-2.5= -6.875   ...
The value of f(-2.5)= -6.875   ...
The value of  | f(-2.5) -  p-2.5 = 0.0  ...



xa= -2.2
The value of p-2.2= -2.2880000000000025   ...
The value of f(-2.2)= -2.288000000000002   ...
The value of  | f(-2.2) -  p-2.2 = 4.440892098500626e-16  ...



xa= -1.5
The value of p-1.5= 3.375   ...
The value of f(-1.5)= 3.375   ...
The value of  | f(-1.5) -  p-1.5 = 0.0  ...



xa= 0.5
The value of p0.5= -3.125   ...
The value of f(0.5)= -3.125   ...
The value of  | f(0.5) -  p0.5 = 0.0  ...



xa= 1.5
The value of p1.5= -7.875   ...
The value of f(1.5)= -7.875   ...
The value of  | f(1.5) -  p1.5 = 0.0  ...



xa= 2.2
The value of p2.2= -7.391999999999999   ...
The value of f(2.2)= -7.391999999999999   ...
The value of  | f(2.2) -  p2.2 = 0.0  ...



>>> 

沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

 WOKWI DHT22 & LED , Node-Red + SQLite database Node-Red程式 [{"id":"6f0240353e534bbd","type":"comment&...