% a quick demo of Horner's method and its effects

clear all
close all

% first a comparison of ways to compute

x = 0.988:.0001:1.012;
y1 = x.^7-7*x.^6+21*x.^5-35*x.^4+35*x.^3-21*x.^2+7*x-1;
plot(x,y1)
pause

% because this polynomial can be nicely factored ...

y2 = (x-1).^7;
plot(x,y2)
pause

% but in general (when nice factors don't exist or you can't find them!), 
% it is best to use Horner's method

y3=-1+x.*(7+x.*(-21+x.*(35+x.*(-35+x.*(21+x.*(-7+x))))));

% note this is best implemented as a loop
% we have to hardcode the polynomial coefficients in a vector

p = [-1 7 -21 35 -35 21 -7 1];
y3 = p(end)*ones(1,length(x));

for i=length(p)-1:-1:1,
  y3 = x.*y3 + p(i);  
end

plot(x,y1,'r--',x,y3)
pause
