juliaijulia-notebook

MethodError: no method matching Lagrange_Polynomials


This is the error message

MethodError: no method matching Lagrange_Polynomials(::Float64, ::LinRange{Float64}, ::Array{Float64,1})
Closest candidates are:Lagrange_Polynomials(::T, !Matched::Array{T,1}, ::Array{T,1}) where T<:AbstractFloat at In[17]:3

This is the code:

using PyPlot

function Lagrange_Polynomials(x::T,vector_x::Vector{T},vector_y::Vector{T}) where T <: AbstractFloat # define an infinitely many large set of functions
n = length(vector_x)
length(vector_y)==n  || error("Incompatible vector size")
S = zero(T)
for i ∈ 1:n
     P = one(T)
          for j ∈ 1:n
                   if j != i
                     P*=(x-vector_x[j])/(vector_x[i]-vector_x[j])
                   end  #chiude l'if
          end    #chiude il ciclo for interno
    S += vector_y[i]*P
end       #chiude il ciclo for esterno
 return S

f(x) = 1/sqrt(2π)*exp(-x^2/2);
a=-2;                                      #estremi dell' intervallo
b = 2;
n = 12                                     #number of interpolating points
vector_x = LinRange(a,b,n);                  #suddivisione dell' intervallo [a,b] in n punti equispaziati
xinterval = LinRange(a,b,1024);            #Una suddivisione più precisa dell' intervallo
ypoly = [Lagrange_Polynomials(x,vector_x,f.(vector_x)) for x in xinterval]
plot(xinterval, ypoly)
plot(xinterval, f.(xinterval), "k");
plot(vector_x, f.(vector_x), "ro");
plt[:legend](["f(x)","interpolation points",L"L_{n-1}(x)"])

Solution

  • you should change Vector{T} to AbstractVector{T} or even delete it

    julia> LinRange(1,2,10) isa Vector
    false
    
    julia> LinRange(1,2,10) isa AbstractVector
    true