Variables interfering with each other

Dear all,
I am implementing the divided differences of Newton’ polynomial. However a strange thing happens.
I define the x and y values by X and Y variables. Inside the function I define the vector \Delta Y = Y.
But, at the end of the execution, I miss the Y value (because \Delta Y changes).
How can I fix this?
Below, my code:

function Diferencas_Divididas(X,Y)
    n=length(X)
    Δy = Y
    a = zeros(n)
    a[1] = Y[1]

    for i in 1:n-1
        for j in 1:n-i
            Δy[j] = (Δy[j+1] - Δy[j]) / (X[j+i] - X[j])
        end
        a[i+1] = Δy[1]
    end
    return a
end

X = [2 2.5 3 3.5]
Y = [7.4 12.2 20.1 33.4]
n=length(X)

a = Diferencas_Divididas(X,Y)

julia> Y
1×4 Array{Float64,2}:
 3.06667  10.8  26.6  33.4

julia> 
´´´

You probably want Δy = copy(Y). Otherwise Δy and Y will refer to the same object.

1 Like

You need Δy = copy(Y)

then

julia> a = Diferencas_Divididas(X,Y)
4-element Vector{Float64}:
 7.4
 9.599999999999998
 6.200000000000006
 3.0666666666666558

julia> Y
1×4 Matrix{Float64}:
 7.4  12.2  20.1  33.4