Create a symbolic interpolating polynomial in Scilab

I made a code to calculate the result of the method of divided differences and the method of lagrange by interpolating points. I would also like to build a polynomial using symbolic variables, but how can I do this?

function dividedDifferences(X,Y,x)
    ddMatrix = X'
    ddMatrix(:,2) = Y'
    for j=3:length(Y)+3
        for i=1:length(Y)+2-j
            ddMatrix(i,j) = (ddMatrix(i,j-1)-ddMatrix(i+1,j-1))/(ddMatrix(i,1)-ddMatrix(i+j-2,1))
        end
    end
    disp(ddMatrix)

    Px = 0
    for j=2:length(Y)+1
        prd = 1
        for i=1:j-2
            prd = prd * (x - ddMatrix(i,1))
        end
        Px = Px + ddMatrix(1,j)*prd
    end
    disp(Px)   
    endfunction

    function lagrange(X,Y,x)
    for i=1:length(Y)
        l(i)=1
        for j=1:length(Y)
            if i~=j
                l(i) = l(i)*(x-X(j))/(X(i)-X(j))
            end
        end
    end
    disp(l')

    L=0
    for i=1:length(Y)
        L = L+Y(i)*l(i)
    end
    disp(L)
endfunction

//example instance
X = [0 1 5 8]
Y = [0 1 8 16.4]
x = 7

dividedDifferences(X,Y,x)
lagrange(X,Y,x)
+3
source share
1 answer

To create a symbolic polynomial, initialize the symbolic variable with x = poly(0,"x"), where x is the name of the variable to be used in the polynomial. Then proceed to computing it in the same way as in a function lagrange. I essentially copied your function to symboliclagrangebelow, cutting out a numerical parameter and an intermediate display:

function symboliclagrange(X,Y)
    x = poly(0,"x")
    for i=1:length(Y)
        l(i)=1
        for j=1:length(Y)
            if i~=j
                l(i) = l(i)*(x-X(j))/(X(i)-X(j))
            end
        end
    end
    L=0
    for i=1:length(Y)
        L = L+Y(i)*l(i)
    end
    disp(L)
endfunction

X = [0 1 5 8], Y = [0 1 8 16.4] 0,85x + 0,15x 2 .

+1

Source: https://habr.com/ru/post/1621133/


All Articles