2019年2月20日 星期三

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

Julia語言 Lagrange 插值法

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

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

程式

#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],[0.0,0.693,1.099])
xa=1.5
a=interpolantfunc(xa)   #returns 0.38237

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


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

沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

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