SciLab中多项式的评估

问题描述 投票:0回答:3

你能帮我在我的代码中发现错误吗?我需要计算多项式,参数是向量和变量的值。我不被允许使用电源标志(^)我有这个代码,但它不起作用,我不知道我做错了什么。

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
polynomial-math scilab
3个回答
1
投票

我首先重构你的代码,删除j = 0的情况,因为这不会改变任何东西,因为x=x它可以从j = 1开始跳过。我还添加了一些调试打印:

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

之后很明显,每次都会乘以相同的x:

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 

还会发生的是,您将f的值更新为最高期限,而忽略任何其他条款。我认为你的意思是返回所有条款

所以你应该创建一个本地x,它会为每个术语重置。

工作实例

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))

0
投票

你应该做的是实施霍纳计划。

f=V(n)
for i from n-1 down to 0 do
    f = f*x
    f = f+V(i)
end for
return f

在问题中,返回值数组V(i)* x ^(2 ^ i),在上一个答案中,返回了计算项V(i)* x ^ i的数组,但是多项式的值是这些条款的总和。

请详细说明输入格式。 V是一个索引范围为1:n的数组吗?指数和学位之间的预期关系是什么?


0
投票

Scilab已经具有horner功能,因此您无需重新发明轮子。例如,要评估1+2*x+4*x^2+8*x^3中的多项式x=-1,0,1,您可以按如下方式进行:

p = poly([1 2 4 8],'x','coeff')
pval = horner(p,[-1 0 1])

产生以下输出

--> p = poly([1 2 4 8],'x','coeff')
 p  = 
            2    3
   1 +2x +4x  +8x

--> pval = horner(p,[-1 0 1])
 pval  = 

  -5.   1.   15.
© www.soinside.com 2019 - 2024. All rights reserved.