Horner's rule for polynomial evaluation: Difference between revisions

m
Line 576:
>>> horner( (-19, 7, -4, 6), 3)
128</lang>
 
=={{header|REXX}}==
<lang rexx>
/*REXX program using Horner's rule for polynomial evaulation. */
 
arg 'X=' x poly /*get value of X and coefficients*/
equ='' /*start with equation clean slate*/
 
/*works for any degree equation. */
do deg=0 until poly=='' /*get the equation's coefficents.*/
parse var poly c.deg poly /*get a equation coefficent. */
c.deg=(c.deg+0)/1 /*normalize it (add 1, div by 1)*/
if c.deg>=0 then c.deg='+'c.deg /*if positive, then preprend a + */
equ=equ c.deg /*concatenate it to the equation.*/
if deg\==0 &, /*if not the first coefficient & */
c.deg\=0 then equ=equ 'x^'deg /* not 0, append power (^) of X.*/
equ=equ ' ' /*insert some blanks, look pretty*/
end
 
say ' x=' x
say ' degree=' deg
say 'equation=' equ
a=c.deg
 
do j=deg by -1 to 1 /*apply Horner's rule to evaulate*/
jm1=j-1
a=a*x + c.jm1
end
 
say ' answer=' a
</lang>
Output when the following is used for input:
x=3 -19 7 -4 6
<pre style="height:12ex;overflow:scroll">
x= 3
degree= 3
equation= -19 +7 x^1 -4 x^2 +6 x^3
answer= 128
</pre>
 
=={{header|R}}==