2018年12月26日 星期三

使用Python 語言 Newton Forward Interpolation EX1-9


Newton Forward  Interpolation

使用Python 語言

#Program to interpolate using newton forward interpolation

# calculating u mentioned in the formula
def u_cal( u, n) :
    temp = u
    for i in range (1,n+1):
        temp = temp * (u - i)
    return temp


#calculating factorial of given number n
def fact(n) :
    f = 1
    for i in range (2,n+1):
        f *= i
    return f

# Number of values given
from array import *

n=4
x=[45, 50, 55, 60]
#y[][] is used for difference table with y[][0] used for input
y= [ [0.7071 , 0.0, 0.0, 0.0, 0.0, 0.0 , 0.0] ,
     [0.7660 , 0.0, 0.0, 0.0, 0.0, 0.0 , 0.0] ,
     [0.8192 , 0.0, 0.0, 0.0, 0.0, 0.0 , 0.0] ,
     [0.8660 , 0.0, 0.0, 0.0, 0.0, 0.0 , 0.0] ]

# Calculating the forward difference table
for i in range (1,n):
     for j in range (0,n-i):
         (y[j][i]) = (y[j + 1][i - 1] - y[j][i - 1])


#Displaying the forward difference table
for i in range (0,n):
    print(x[i],'\t',end='')
    for j in range (0,n-i): 
        print(y[i][j],'\t',end='')
    print('\n')   

#Value to interpolate at
value = 52.0;
#initializing u and sum
sum = y[0][0]
u = (value - x[0]) / (x[1] - x[0])
for i in range (1,n):
    sum = sum + (u_cal(u, i) * y[0][i])/fact(i)

print('\n Value at', value ,' is ',sum )


'''
============= RESTART: H:/2018-09勤益科大數值分析/數值分析/PYTHON/Ex1-9-2.py =============
45 0.7071 0.05890000000000006 -0.005700000000000038 -0.0007000000000000339

50 0.766 0.053200000000000025 -0.006400000000000072

55 0.8192 0.04679999999999995

60 0.866


 Value at 52.0  is  0.74097888
>>>


Output:

  45    0.7071    0.0589    -0.00569999    -0.000699997   
  50    0.766    0.0532    -0.00639999   
  55    0.8192    0.0468   
  60    0.866   

  Value at 52 is 0.788003
'''

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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