2019年2月22日 星期五

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

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

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

程式
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


x = [1.0 , 2.0 , 3.0 ,4.0 ]
f = [0.0 , 0.693 , 1.099 , 1.386]
xa = 1.5
result1 = lagrange(x,f,xa)
println("Lagrange 內插法理則 ")
println("x=    " , x)
println("f(x)= " , f)
   
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)


輸出畫面
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

沒有留言:

張貼留言

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> &...