2019年3月5日 星期二

Julia語言例題1-5 已知函數f(x)=ln(x)請使用Lagrange 內插法 求f(1.5) ,f(2.5) f(3.5)的P(x)與f(x) 分別用x=1.5 ,2.5 ,3.5 計算f(x)的e(x)誤差值

Julia語言例題1-5 已知函數f(x)=ln(x) 
xi     f(xi)
==============
1.0    0.000
2.0    0.693
3.0    1.099
4.0    1.386
請使用Lagrange 內插法 求f(1.5) ,f(2.5) f(3.5)的P(x)與f(x) 
分別用x=1.5 ,2.5 ,3.5 計算f(x)的e(x)誤差值

using Printf

function lagrange(x::Array{Float64,1},f::Array{Float64,1},xa::Float64)
    #
    # implements the interpolation algorithm of Newton
    #
    # ON ENTRY :
    # x abscisses, given as a column vector;
    # f ordinates, given as a column vector;
    # xa point where to evaluate the interpolating
    # polynomial through (x[i],f[i]).
    #
    # ON RETURN :
    # d divided differences, computed from and f;
    # p value of the interpolating polynomial at xa.
    #
    # EXAMPLE :
    n = length(x)
    tmp2=0.0
    for k=1:n
        tmp1=1.0
        for i=1:n
            if (i != k)
                tmp1 *= (xa-x[i]) / (x[k]-x[i])
            end    
        end
        tmp2=tmp2+tmp1*f[k]    
    end    
        
    return tmp2
end


function er(xa::Float64,x0::Float64,x1::Float64,x2::Float64,x3::Float64)
    tmp1=0.0
    tmp2=0.0
    sum=1.0
    xm=(x[1]+x[length(x)])/2
    #println(xm)
    for i=1:length(x)
        sum=sum*i
    end 
    #println(sum)
    tmp1=(xa-x0)*(xa-x1)*(xa-x2)*(xa-x3)/sum
    #println(tmp1)
    tmp2=tmp1*(-6/xm^4)
    return tmp2
end

x= [1.0 ,2.0 , 3.0 , 4.0] 
f= [0.0,0.693,1.099,1.386]
xb = [ 1.5 , 2.5 ,3.5]

for i = 1:length(xb)
    xa=xb[i]
    result1 = lagrange(x,f,xa)
    println("Lagrange 內插法理則 ")
    println("x=    " , x)
    println("f(x)= " , f)
    println("xa=   " , xa)
    
   
    s = @sprintf("Pn(x)=%0.5f" , result1 )
    println(s)
    s = @sprintf("f(xa)=%0.5f" , log(xa) )
    println(s)
    s = @sprintf("誤差 =%0.5f" , abs(log(xa)-result1) )
    println(s)
    println()

end

for i=1:length(xb)
    result2=0.0
    xa=xb[i]
    x0=x[1]
    x1=x[2]
    x2=x[3]
    x3=x[4]
    result2= er(xa, x0 ,x1 , x2 , x3)
    s=@sprintf("x= %0.2f 誤差e(x)=%0.5f",xa ,result2)
    println(s)
end    






輸出畫面
Lagrange 內插法理則 
x=    [1.0, 2.0, 3.0, 4.0]
f(x)= [0.0, 0.693, 1.099, 1.386]
xa=   1.5
Pn(x)=0.39287
f(xa)=0.40547
誤差 =0.01259

Lagrange 內插法理則 
x=    [1.0, 2.0, 3.0, 4.0]
f(x)= [0.0, 0.693, 1.099, 1.386]
xa=   2.5
Pn(x)=0.92138
f(xa)=0.91629
誤差 =0.00508

Lagrange 內插法理則 
x=    [1.0, 2.0, 3.0, 4.0]
f(x)= [0.0, 0.693, 1.099, 1.386]
xa=   3.5
Pn(x)=1.24687
f(xa)=1.25276
誤差 =0.00589

x= 1.50 誤差e(x)=0.00600
x= 2.50 誤差e(x)=-0.00360
x= 3.50 誤差e(x)=0.00600

沒有留言:

張貼留言

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

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