%mathpiper,def="Horner"

Horner(_e,_v) <--
[
  Local(uni,coefs,result);
  uni := MakeUni(e,v);
  coefs:=DestructiveReverse(uni[3]);
  result:=0;

  While(coefs != {})
  [
    result := result*v;
    result := result+First(coefs);
    coefs  := Rest(coefs);
  ];
  result:=result*v^uni[2];
  result;
];

%/mathpiper



%mathpiper_docs,name="Horner",categories="User Functions;Polynomials (Operations)"
*CMD Horner --- convert a polynomial into the Horner form
*STD
*CALL
	Horner(expr, var)

*PARMS

{expr} -- a polynomial in "var"

{var} -- a variable

*DESC

This command turns the polynomial "expr", considered as a univariate
polynomial in "var", into Horner form. A polynomial in normal form
is an expression such as
$$c[0] + c[1]*x + ... + c[n]*x^n$$.

If one converts this polynomial into Horner form, one gets the
equivalent expression
$$(...( c[n] * x + c[n-1] ) * x + ...  + c[1] ) * x + c[0]$$.

Both expression are equal, but the latter form gives a more
efficient way to evaluate the polynomial as  the powers have
disappeared.

*E.G.

In> expr1:=Expand((1+x)^4)
Result: x^4+4*x^3+6*x^2+4*x+1;
In> Horner(expr1,x)
Result: (((x+4)*x+6)*x+4)*x+1;

*SEE Expand, ExpandBrackets, EvaluateHornerScheme
%/mathpiper_docs