2019年2月12日 星期二

習題1-2 f(x)=sin(x) x以度為單位 請用Lagrange內差法求 xa=[10.5 , 11.5 .12.5 ] 之值

習題1-2 已知

x=[10.0 , 11.0 ,12.0 ,13.0]
f=[0.1736 , 0.1908 , 0.2079 , 0.2250]

f(x)=sin(x)  x以度為單位
請用Lagrange內差法求

xa=[10.5 , 11.5 .12.5 ] 之值


Python程式


'''
n=3
xa=[10.5 , 11.5 .12.5 ]
x=[10.0 , 11.0 ,12.0 ,13.0]
f=[0.1736 , 0.1908 , 0.2079 , 0.2250]

/* 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.sin(x))


print('\nLagrange Interpolation Algorithm\n')


xa=[10.5 , 11.5 , 12.5 ]

x=[10.0 , 11.0 , 12.0 ,13.0]
f=[0.1736 , 0.1908 , 0.2079 , 0.2250]
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]

    print('The value of p' ,round(indata,6) , '= ' , round(result,6) , '   ...')
 
    resultfx=fx(indata * ( math.pi/ 180 ))   #角度轉徑度
    print( 'The value of f(' , round(indata,6) , ')= ' , round(resultfx,6) , '   ...')
 
    print('The value of  | f(' , round(indata,6) , ') -  p' , round(indata,6) , ' = ' , round( (abs(resultfx - result)),6 ) , '  ...')
    print("\n\n")
 


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

Lagrange Interpolation Algorithm

x= [10.0, 11.0, 12.0, 13.0]
f= [0.1736, 0.1908, 0.2079, 0.225]
xa= [10.5, 11.5, 12.5]


xa= 10.5
The value of p 10.5 =  0.182219    ...
The value of f( 10.5 )=  0.182236    ...
The value of  | f( 10.5 ) -  p 10.5  =  1.7e-05   ...



xa= 11.5
The value of p 11.5 =  0.199356    ...
The value of f( 11.5 )=  0.199368    ...
The value of  | f( 11.5 ) -  p 11.5  =  1.2e-05   ...



xa= 12.5
The value of p 12.5 =  0.216444    ...
The value of f( 12.5 )=  0.21644    ...
The value of  | f( 12.5 ) -  p 12.5  =  4e-06   ...



>>> 

沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

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