2019年2月12日 星期二

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

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

x       f(x)
============
0.0   0.00
1.0  -3.00
2.0   0.00
34.0  15.00
============

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


Python程式
'''
n=3
xa=[0.5 , 1.5 .2.5  ,3.5]

0..0   0.00
1.0  -3.00
2.0   0.00
3.0  15.00

/* pr1-1-a.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)-4*x)


print('\nLagrange Interpolation Algorithm\n')

xa=[0.5 , 1.5 ,  2.5  ,3.5]

x=[0.0 , 1.0 , 2.0 , 3.0]
f=[0.0 , -3.0 , 0.0 , 15.0]
n=3  # 4 point n=3


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.py ============

Lagrange Interpolation Algorithm

x= [0.0, 1.0, 2.0, 3.0]
f= [0.0, -3.0, 0.0, 15.0]
xa= [0.5, 1.5, 2.5, 3.5]


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



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



xa= 2.5
The value of p2.5= 5.625   ...
The value of f(2.5)= 5.625   ...
The value of  | f(2.5) -  p2.5 = 0.0  ...



xa= 3.5
The value of p3.5= 28.875   ...
The value of f(3.5)= 28.875   ...
The value of  | f(3.5) -  p3.5 = 0.0  ...


>>>
FOOPLOT 繪製 math.pow(x,3)-4*x 



沒有留言:

張貼留言

2024產專班 作業2

 2024產專班 作業2   1. 系統圖       ESP32+MFRC522 組成RFID Reader 可以將RFID卡片的UID 透過 MQTT協定    上傳(發行 主題 (:topic) alex9ufo/2024/RFID/RFID_UID  ,, Payload...