2019年1月31日 星期四

例題1-5 多項式 Lagrange內插法 f (x) = log (x) 求x=1.5 , 2.5 , 3.5 f(x)之值 = ? 並計算誤差值=?

例題1-5 多項式 Lagrange內插法
f (x) = ln (x)

已知 平面上4點

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

求x=1.5 , 2.5 , 3.5   f(x)之值 = ?
並計算誤差值=?



#/********** Lagrange's interpolation ***************/
import math

def f(x):
    return math.log(x)

n=4
x= [0.0 for i in range(n+1)]     #x [n] 矩陣
y= [0.0 for i in range(n+1)]     #f [n] 矩陣
x=[1.0 , 2.0  ,3.0 , 4.0]
y=[0.0 , 0.693 , 1.099 ,1.386 ]

n1=3
P=[1.5 , 2.5 , 3.5]
Px=[0.0 , 0.0 , 0.0]

#f(x)=log(x)
a=1.5   #x=1.5 求 f(1.5)= ?

print("\nEnter the number of the terms of the table: ",n)
print("\nEnter the respective values of the variables x and y: \n")
print("The values of x =")
for i  in range (0,n) :     #
    print( round( x[i],4),"\t",end='')
print()
print("The values of y =")
for i  in range (0,n) :     #
    print( round( y[i],4),"\t",end='')

print("\nEnter the value of the x to find the respective value of y ")
for i  in range (0,n1) :     #
    print( round( P[i],4),"\t",end='')
print()

for m in range (0 , n1):
    a=P[m]
    k=0.0
    for i in range(0, n):
        s=1.0
        t=1.0
        for j in range(0,n):
            if(j!=i):
                s=s*(a-x[j]);
                t=t*(x[i]-x[j]);
        k=k+((s/t)*y[i]);
    Px[m]=k
    print("\nThe {%.2f} to find respective value of the variable y is: {%.6f}" %(a, k))
 
print(" \nx\t\tP(x)\t\t\tf(x)\t\t\t|f(x)-P(x)|")
for i in range (0 , n1):
    print ("{%2.3f}\t\t{%5.6f}\t\t{%5.6f}\t\t{%5.6f}" %(P[i],Px[i], f(P[i]), abs(Px[i]-f(P[i]) ) ) )




輸出畫面
========= RESTART: F:/2018-09勤益科大數值分析/數值分析/PYTHON/EX1-5.py ============

Enter the number of the terms of the table:  4

Enter the respective values of the variables x and y: 

The values of x =
1.0 2.0 3.0 4.0
The values of y =
0.0 0.693 1.099 1.386
Enter the value of the x to find the respective value of y 
1.5 2.5 3.5

The {1.50} to find respective value of the variable y is: {0.392875}

The {2.50} to find respective value of the variable y is: {0.921375}

The {3.50} to find respective value of the variable y is: {1.246875}

x P(x) f(x) |f(x)-P(x)|
{1.500} {0.392875} {0.405465} {0.012590}
{2.500} {0.921375} {0.916291} {0.005084}
{3.500} {1.246875} {1.252763} {0.005888}
>>> 

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...