2019年2月20日 星期三

Julia語言 範例1-3 通過下面4點的Lagrange內插法求P(1.5)之值?

Julia語言 範例1-3 通過下面4點的Lagrange內插法求P(1.5)之值?

(1 , 0.0)  (2 , 0.693)  (3 , 1.099)  (4 , 1.386)

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


=====程式======

using Printf


#This function returns another function, which is the Lagrange Interpolant of the values xvals and yvals.
function LagrangeInterpolantGenerator(xvals,yvals)
    function LagrangeInterpolant(x)
        numvalstoevaluate = length(x)
        numvalstoevaluate == 1 ? output = 0 : output = zeros(numvalstoevaluate)
        for k = 1:numvalstoevaluate
            N = length(xvals)
            LagrangePolynomials = ones(N)
            for i in 1:N  
                for j in [1:i-1;i+1:N]     #Surprisingly, this works even in the i=1 and i=N cases.
                    LagrangePolynomials[i] = LagrangePolynomials[i].*(x[k]-xvals[j])./(xvals[i]-xvals[j])
                end
            end
            numvalstoevaluate == 1 ? output = sum(LagrangePolynomials.*yvals) : output[k] = sum(LagrangePolynomials.*yvals)
        end
        return output
    end
    return LagrangeInterpolant
end

#Examples
interpolantfunc = LagrangeInterpolantGenerator([1.0,2.0 , 3.0 , 4.0 ], [0.0,0.693 ,1.099 , 1.386] )
xa=1.5
a=interpolantfunc(xa)   #returns  0.34650 

s = @sprintf("Lagrange插值法 P(%0.2f) = %0.5f " , float(xa) , float(a) )
println(s)

輸出畫面
Lagrange插值法 P(1.50) = 0.39287 

沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

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