滿足f(x)=ln (x) 的數據
(1)
x = ([1.0,2.0,3.0,4.0])
f (x)= ([0.0,0.693,1.099,1.386])
(2)
x=[1.0 , 1.2 , 1.4 , 2.0]
f(x)=[0.0 , 0.182 , 0.336 , 0.693]
(3)
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]
計算P(1.5) 之值=??
程式
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
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]]
y= [[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]]
for i = 1:3
interpolantfunc = LagrangeInterpolantGenerator(x[i],y[i] )
xa=1.5
a=interpolantfunc(xa) #returns 0.34650
s = @sprintf("Lagrange插值法 P(%0.2f) = %0.5f " , float(xa) , float(a) )
println(s)
end
輸出畫面
Lagrange插值法 P(1.50) = 0.39287
Lagrange插值法 P(1.50) = 0.40447
Lagrange插值法 P(1.50) = 0.40614
沒有留言:
張貼留言