2019年2月12日 星期二

習題1-1-d 根據下面的已知點撰寫Lagrange 內差法程式 並計算 xa=[150 ,250 ,350 ,450 ,550 , 650 ]之值

習題1-1-d
根據下面的已知點撰寫Lagrange 內差法程式
並計算 xa=[150 ,250 ,350 ,450 ,550 , 650 ]之值

'''
n=5
x= [100, 200, 300 ,400, 500 ,600]
f(x)=[1700 , 1000 ,833 , 800 ,820 , 867]
xa=[150 ,250 ,350 ,450 ,550 , 650 ]


/* 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 (x + (160000/x))


print('\nLagrange Interpolation Algorithm\n')


x= [100, 200, 300 ,400, 500 ,600]
f=[1700 , 1000 ,833 , 800 ,820 , 867]
xa=[150 ,250 ,350 ,450 ,550 , 650 ]
n=5  # 6 point n=5

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

Lagrange Interpolation Algorithm

x= [100, 200, 300, 400, 500, 600]
f= [1700, 1000, 833, 800, 820, 867]
xa= [150, 250, 350, 450, 550, 650]


xa= 150
The value of p150= 1238.8242187499998   ...
The value of f(150)= 1216.6666666666667   ...
The value of  | f(150) -  p150 = 22.15755208333303  ...



xa= 250
The value of p250= 885.34765625   ...
The value of f(250)= 890.0   ...
The value of  | f(250) -  p250 = 4.65234375  ...



xa= 350
The value of p350= 809.18359375   ...
The value of f(350)= 807.1428571428571   ...
The value of  | f(350) -  p350 = 2.0407366071428896  ...



xa= 450
The value of p450= 803.2070312500001   ...
The value of f(450)= 805.5555555555555   ...
The value of  | f(450) -  p450 = 2.3485243055554292  ...



xa= 550
The value of p550= 846.79296875   ...
The value of f(550)= 840.909090909091   ...
The value of  | f(550) -  p550 = 5.883877840909008  ...



xa= 650
The value of p650= 842.81640625   ...
The value of f(650)= 896.1538461538462   ...
The value of  | f(650) -  p650 = 53.33743990384619  ...



>>> 

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...