Luke Niu
Luke Niu

Reputation: 171

How can I correct the bug in my Julia program for Lagrange Interpolation

I want to build an algorithm program for Lagrange interpolation to process my data and exercise my algorithm ability. The programming language is JuliaLang.

using DelimitedFiles
using Plots; pyplot()

function lagrange_interpolate(X,Y,t)
    C = ones(length(X))
    d = 0.0
    for i = 1:length(X)
        for j = [1:i-1;i+1:length(X)]
            C[j] = C[j]*(t-X[j])/(X[i]-X[j])
        end
        d = d + Y[i] * C[i]
    end
    return d
end

A = readdlm("Numerical Methods/Data/data02.dat")
X = view(A,:,1)
Y = view(A,:,2)
T = 1.0:0.1:2.0
U = lagrange_interpolate.(X,Y,T)

plot([X;T],[Y;U])

savefig("U.png")

The data02.dat:

0.0 0.0024979173609870897
0.1 0.03946950299855745
0.2 0.11757890635775581
0.3 0.22984884706593012
0.4 0.3662505856877064
0.5 0.5145997611506444
0.6 0.6616447834317517
0.7 0.7942505586276727
0.8 0.900571807773467
0.9 0.9711111703343291
1.0 0.9995675751366397

But it will get the wrong result. I want to know how to correct it.

My result

Upvotes: 1

Views: 457

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69869

There are two problems.

First you have a bug in your method. Here is a fix:

function lagrange_interpolate(X,Y,t)
    C = ones(length(X))
    d = 0.0
    for i = 1:length(X)
        for j = [1:i-1;i+1:length(X)]
            C[i] = C[i]*(t-X[j])/(X[i]-X[j])
        end
        d = d + Y[i] * C[i]
    end
    return d
end

an even simpler approach would be to write:

function lagrange_interpolate(X,Y,t)
    idxs = eachindex(X)
    sum(Y[i] * prod((t-X[j])/(X[i]-X[j]) for j in idxs if j != i) for i in idxs)
end

The second problem is that you apply broadcasting incorrectly. You should write:

lagrange_interpolate.(Ref(X), Ref(Y), T)

because you do not want X and Y to be broadcasted over (and Ref protects the value wrapped in it from broadcasting, see https://docs.julialang.org/en/latest/manual/arrays/#Broadcasting-1).

Also in this case maybe using a comprehension like this:

[lagrange_interpolate(X, Y, t) for t in T]

would be easier to read (but it is a matter of style).

Upvotes: 2

Related Questions