2019年2月22日 星期五

Julia語言 例題1-4 利用Lagrange 已知下列數據 求 xa=1.5 的值並計算誤差值=?

Julia語言 例題1-4 利用Lagrange 已知下列數據 求 xa=1.5
的值並計算誤差值=?  真實值f(x)=ln(x) , f(1.5)=ln(1.5=0.405
===============
(1)
xa=1.5
1.0  0.0
2.0  0.693
3.0  1.099
4.0  1.386
===============
(2)
xa=1.5
1.0  0.000
1.2  0.182
1.4  0.336
2.0  0.693
===============
(3)
xa=1.5
1.0  0.000
1.2  0.182
1.7  0.531
2.0  0.693
2.2  0.788
2.7  0.993
3.0  1.099
3.2  1.163
3.7  1.308
4.0  1.386
===============
程式
using Printf

function lagrange(x1::Array{Float64,1},f1::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(x1)
    tmp2=0.0
    for k=1:n
        tmp1=1.0
        for i=1:n
            if (i != k)
                tmp1 *= (xa-x1[i]) / (x1[k]-x1[i])
            end 
        end
        tmp2=tmp2+tmp1*f1[k] 
    end 
     
    return tmp2
end


x = [ [1.0 , 2.0 ,3.0 , 4.0],
      [1.0 , 1.2 ,1.4 , 2.0],
      [1.0 , 1.2 , 1.7 , 2.0  , 2.2 ,  2.7  , 3.0 , 3.2  , 3.7  , 4.0]]
   
f = [ [0.0 , 0.693 , 1.099 , 1.386],
      [0.0 , 0.182 , 0.336 , 0.693],
      [0.0 , 0.182 , 0.531 , 0.693  , 0.788  ,  0.993 , 1.099 , 1.163 , 1.308 , 1.386] ]
     
xa = 1.5
for m=1:3
    x1=x[m]
    f1=f[m]
    result1 = lagrange(x1,f1,xa)
    println("Lagrange 內插法理則 ")
    println("x=    " , x1)
    println("f(x)= " , f1)
 
    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

輸出畫面

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

Lagrange 內插法理則 
x=    [1.0, 1.2, 1.4, 2.0]
f(x)= [0.0, 0.182, 0.336, 0.693]
Pn(x)=0.40447
f(xa)=0.40547
誤差 =0.00100

Lagrange 內插法理則 
x=    [1.0, 1.2, 1.7, 2.0, 2.2, 2.7, 3.0, 3.2, 3.7, 4.0]
f(x)= [0.0, 0.182, 0.531, 0.693, 0.788, 0.993, 1.099, 1.163, 1.308, 1.386]
Pn(x)=0.40614
f(xa)=0.40547
誤差 =0.00068


沒有留言:

張貼留言

2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2

 2024年4月24日 星期三 Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --2 AngularJS 實例 <!DOCTYPE html> <html> <head> &...