Search code examples
polynomial-mathscilab

Evaluation of a polynomial in SciLab


Could you please help me find a mistake in my code? I need to calculate the polynomial, with parameters the vector and the value of the variable. I am not allowed to use the power sign (^) I have got this code but it doesn't work and I don't see what I am doing wrong.

function f=veelTermEvaluatie(V,x)
        f=V(1);
        for i=2:length(V)
            for j=0:i-1
                if j=0 then x=x
                    else x=x*x
                end
                f=V(i)*x
            end
        end
    endfunction

    V=[1 2 3 4 5 6]
    x=3

Solution

  • I first refactored your code, to remove the j=0 situation, since this does not change anything since x=x it can be skipped by starting at j=1. I also added some debug printing :

    function f=veelTermEvaluatie(V,x)
        f=V(1);
    
        for i=2:length(V)
    
            printf("\nI: %d --> ", i)            
            for j=1:i-1                
                x = x * x
                printf("j: %d, x=%d ",j,x)
            end
    
            f=V(i)*x
        end
    
        return f
    endfunction
    

    After that it became clear that you multiply the same x, each and every time:

    I: 2 --> j: 1, x=9 
    I: 3 --> j: 1, x=81 j: 2, x=6561 
    I: 4 --> j: 1, x=43046721 j: 2, x=-501334399 j: 3, x=0 
    I: 5 --> j: 1, x=0 j: 2, x=0 j: 3, x=0 j: 4, x=Inf 
    I: 6 --> j: 1, x=Inf j: 2, x=Inf j: 3, x=Inf j: 4, x=Inf j: 5, x=Inf 
    

    What also happens is that you update the value of f to the highest term, disregarding any other terms. I think your meaning is to return all terms

    So you should create a local x which is reset for every term.

    Working example

    function f=veelTermEvaluatie(V,x)
    
        //Initialize the result to be a copy of the input
        f=V;
    
        // For each element in the input (except the first)
        for i=2:length(V)
    
            printf("\nI: %d --> ", i);
            //Initialize a local x variable to the global x
            new_x = x;
    
            for j=1:i-1
                // Update only the local x                 
                new_x = new_x * x;
                printf("j: %d, x=%d ",j,x);
            end
    
            // Multiply the value in the array with the local x value
            f(i)=V(i)*new_x;
        end
    
        return f
    endfunction
    
    V=[1 2 3 4 5 6]
    x=3
    
    result = veelTermEvaluatie(V,x)
    
    disp(result)
    disp(sum(result))