Code Horner的多项式评估方法

问题描述

我正在尝试为Horner的多项式求值方法编码,但由于某种原因,它对我不起作用,我不确定在哪里弄错了。

这些是我拥有的数据:

nodes = [-2,-1,1]
x = 2
c (coefficients) = [-3,3,-1]

到目前为止,我的代码是:

function y = horner(x,nodes,c)

   n = length(c);
   y = c(1);

   for i = 2:n
       y = y * ((x - nodes(i - 1)) + c(i));
   end
end

我应该以诸如(−1)·(x+2)(x+1)+3·(x+2)−3·1之类的多项式结束,如果是x =2,那么我应该得到-3。但是由于某种原因,我不知道我要去哪里错了。

编辑:

所以我更改了代码。我认为可以,但是我不确定:

function y = horner(x,c)
   n = length(c);
   y = c(n);
   for k = n-1:-1:1
       y = c(k) + y * (x - nodes((n - k) + 1));
   end
end

解决方法

这有效:

function y = horner(x,nodes,c)
   n = length(c);
   y = 0;
   for i = 1:n % We iterate over `c`
      tmp = c(i);
      for j = 1:i-1 % We iterate over the relevant elements of `nodes`
          tmp *= x - nodes(j); % We multiply `c(i) * (x - nodes(1)) * (x -nodes(2)) * (x- nodes(3)) * ... * (x - nodes(i -1))
      end
      y += tmp; % We added each product to y
   end
   % Here `y` is as following:
   % c(1) + c(2) * (x - nodes(1)) + c(3) * (x - nodes(1)) * (x - nodes(2)) + ... + c(n) * (x - nodes(1)) * ... * (x - nodes(n - 1))
end
,

(很抱歉这不是 python 但我不知道 python)

在我们没有节点的情况下,horner 的方法是这样工作的:

p = c[n]
for i=n-1 .. 1
    p = x*p + c[i]

例如对于二次方程(具有系数 a,b,c)这是

p = x*(x*a+b)+c

请注意,如果您的语言支持 fma

fma(x,y,x) = x*y+z

那么就可以写出horner的方法

p = c[n]
for i=n-1 .. 1
    p = fma( x,p,c[i])

当你有节点时,改变很简单:

p = c[n]
for i=n-1 .. 1
    p = (x-nodes[i])*p + c[i]

或者,使用 fma

p = c[n]
for i=n-1 .. 1
    p = fma( (x-nodes[i]),c[i])

对于上面的二次方程,这导致

p = (x-nodes[1]*((x-nodes[2])*a+b)+c

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...