Horner's rule for polynomial evaluation: Difference between revisions
Horner's rule for polynomial evaluation (view source)
Revision as of 18:30, 17 March 2024
, 2 months agoAdded Easylang
No edit summary |
(Added Easylang) |
||
(12 intermediate revisions by 9 users not shown) | |||
Line 24:
{{trans|Python}}
<
V acc = 0
L(c) reversed(coeffs)
Line 30:
R acc
print(horner([-19, 7, -4, 6], 3))</
{{out}}
Line 38:
=={{header|360 Assembly}}==
<
HORNER CSECT
USING HORNER,R15 set base register
Line 58:
PG DS CL12 buffer
YREGS
END HORNER</
{{out}}
<pre>
Line 65:
=={{header|ACL2}}==
<
(if (endp ps)
0
(+ (first ps)
(* x (horner (rest ps) x)))))</
=={{header|Action!}}==
<
INT v,i
Line 102:
res=Horner(coeffs,4,x)
PrintF("=%I%E",res)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Horner's_rule_for_polynomial_evaluation.png Screenshot from Atari 8-bit computer]
Line 111:
=={{header|Ada}}==
<
procedure Horners_Rule is
Line 127:
begin
Put(Horner(Coeffs => (-19.0, 7.0, -4.0, 6.0), Val => 3.0), Aft=>1, Exp=>0);
end Horners_Rule;</
Output:
<pre>128.0</pre>
=={{header|Aime}}==
<
horner(list coeffs, real x)
{
Line 154:
0;
}</
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G}}
<
(
REAL res := 0.0;
Line 170:
[4]REAL coeffs := (-19.0, 7.0, -4.0, 6.0);
print( horner(coeffs, 3.0) )
)</
=={{header|ALGOL W}}==
<
% Horner's rule for polynominal evaluation %
% returns the value of the polynominal defined by coefficients, %
Line 199:
write( r_format := "A", r_w := 8, r_d := 2, Horner( coefficients, 4, 3 ) )
end test_cases
end.</
{{out}}
<pre>
Line 207:
=={{header|APL}}==
Works in [[Dyalog APL]]
<syntaxhighlight lang
{{output}}
<pre>
Line 215:
=={{header|ATS}}==
<
"share/atspre_staload.hats"
Line 238:
in
println! (res)
end // end of [main0]</
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">horner: function [coeffs, x][
result: 0
loop reverse coeffs 'c ->
Line 249 ⟶ 248:
]
print horner @[neg 19, 7, neg 4, 6] 3</
{{out}}
<pre>128</pre>
=={{header|AutoHotkey}}==
<
x := 3
Line 271 ⟶ 268:
i := Co0 - A_Index + 1, Result := Result * x + Co%i%
Return, Result
}</
Message box shows:
<pre>128</pre>
=={{header|AWK}}==
<
function horner(x, A) {
acc = 0;
Line 287 ⟶ 284:
split(p,P);
print horner(x,P);
}</
{{out}}
Line 294 ⟶ 291:
128
</pre>
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
<syntaxhighlight lang="qbasic">100 HOME : REM 100 CLS for Chipmunk Basic and GW-BASIC
100 CLS : REM 100 HOME for Applesoft BASIC
110 X = 3
120 DIM COEFFS(3)
130 COEFFS(0) = -19
140 COEFFS(1) = 7
150 COEFFS(2) = -4
160 COEFFS(3) = 6
170 PRINT "Horner's algorithm for the polynomial "
180 PRINT "6*x^3 - 4*x^2 + 7*x - 19 when x = 3 is: ";
190 ACCUM = 0
200 FOR I = 3 TO 0 STEP -1
210 ACCUM = (ACCUM*X)+COEFFS(I)
220 NEXT I
230 PRINT ACCUM
240 END</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="vb">x = 3
dim coeficientes = {-19, 7, -4, 6}
print "Horner's algorithm for the polynomial ";
print "6*x^3 - 4*x^2 + 7*x - 19 when x = 3: ";
print AlgoritmoHorner(coeficientes, x)
end
function AlgoritmoHorner(coeffs, x)
acumulador = 0
for i = coeffs[?]-1 to 0 step -1
acumulador = (acumulador * x) + coeffs[i]
next i
return acumulador
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 CLS
110 x = 3
120 DIM coeffs(3)
130 coeffs(0) = -19
140 coeffs(1) = 7
150 coeffs(2) = -4
160 coeffs(3) = 6
170 PRINT "Horner's algorithm for the polynomial "
180 PRINT "6*x^3 - 4*x^2 + 7*x - 19 when x = 3 is: ";
190 accum = 0
200 FOR i = UBOUND(coeffs,1) TO 0 STEP -1
210 accum = (accum*x)+coeffs(i)
220 NEXT i
230 PRINT accum
240 END</syntaxhighlight>
{{out}}
<pre>Horner's algorithm for the polynomial
6*x^3 - 4*x^2 + 7*x - 19 when x = 3 is: 128</pre>
==={{header|Gambas}}===
<syntaxhighlight lang="vbnet">Public coeficientes As New Integer[4]
Public Function AlgoritmoHorner(coeficientes As Integer[], x As Integer) As Integer
coeficientes[0] = -19
coeficientes[1] = 7
coeficientes[2] = -4
coeficientes[3] = 6
Dim i As Integer, acumulador As Integer = 0
For i = coeficientes.Count - 1 To 0 Step -1
acumulador = (acumulador * x) + coeficientes[i]
Next
Return acumulador
End Function
Public Sub Main()
Dim x As Integer = 3
Print "Horner's algorithm for the polynomial 6*x^3 - 4*x^2 + 7*x - 19 when x = 3: ";
Print AlgoritmoHorner(coeficientes, x)
End </syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
==={{header|GW-BASIC}}===
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
<syntaxhighlight lang="qbasic">100 CLS : REM 100 HOME for Applesoft BASIC
110 X = 3
120 DIM COEFFS(3)
130 COEFFS(0) = -19
140 COEFFS(1) = 7
150 COEFFS(2) = -4
160 COEFFS(3) = 6
170 PRINT "Horner's algorithm for the polynomial "
180 PRINT "6*x^3 - 4*x^2 + 7*x - 19 when x = 3 is: ";
190 ACCUM = 0
200 FOR I = 3 TO 0 STEP -1
210 ACCUM = (ACCUM*X)+COEFFS(I)
220 NEXT I
230 PRINT ACCUM
240 END</syntaxhighlight>
{{out}}
<pre>Same as Chipmunk Basic entry.</pre>
==={{header|Minimal BASIC}}===
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|Applesoft BASIC}}
{{works with|BASICA}}
{{works with|Chipmunk Basic}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{works with|Just BASIC}}
{{works with|Liberty BASIC}}
{{works with|Run BASIC}}
{{works with|Yabasic}}
<syntaxhighlight lang="qbasic">20 LET X = 3
30 DIM C(3)
40 LET C(0) = -19
50 LET C(1) = 7
60 LET C(2) = -4
70 LET C(3) = 6
80 PRINT "HORNER'S ALGORITHM FOR THE POLYNOMIAL"
90 PRINT "6*X^3 - 4*X^2 + 7*X - 19 WHEN X = 3 : ";
100 LET A = 0
110 FOR I = 3 TO 0 STEP -1
120 LET A = (A*X)+C(I)
130 NEXT I
140 PRINT A
150 END</syntaxhighlight>
{{out}}
<pre>Same as Chipmunk Basic entry.</pre>
==={{header|MSX Basic}}===
The [[#Minimal_BASIC|Minimal BASIC]] solution works without any changes.
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
<syntaxhighlight lang="qbasic">FUNCTION Horner (coeffs(), x)
acumulador = 0
FOR i = UBOUND(coeffs) TO LBOUND(coeffs) STEP -1
acumulador = (acumulador * x) + coeffs(i)
NEXT i
Horner = acumulador
END FUNCTION
x = 3
DIM coeffs(3)
DATA -19, 7, -4, 6
FOR a = LBOUND(coeffs) TO UBOUND(coeffs)
READ coeffs(a)
NEXT a
PRINT "Horner's algorithm for the polynomial 6*x^3 - 4*x^2 + 7*x - 19 when x = 3 is: ";
PRINT Horner(coeffs(), x)
END</syntaxhighlight>
==={{header|Quite BASIC}}===
The [[#Minimal_BASIC|Minimal BASIC]] solution works without any changes.
==={{header|Yabasic}}===
<syntaxhighlight lang="vb">x = 3
dim coeffs(4)
coeffs(0) = -19
coeffs(1) = 7
coeffs(2) = -4
coeffs(3) = 6
print "Horner's algorithm for the polynomial ";
print "6*x^3 - 4*x^2 + 7*x - 19 when x = 3: ";
print AlgoritmoHorner(coeffs, x)
end
sub AlgoritmoHorner(coeffs, x)
local acumulador, i
acumulador = 0
for i = arraysize(coeffs(),1) to 0 step -1
acumulador = (acumulador * x) + coeffs(i)
next i
return acumulador
end sub</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
=={{header|Batch File}}==
<
@echo off
Line 320 ⟶ 511:
echo %return%
exit /b
</syntaxhighlight>
{{out}}
<pre>
Line 330 ⟶ 521:
=={{header|BBC BASIC}}==
<
coefficients() = -19, 7, -4, 6
PRINT FNhorner(coefficients(), 3)
Line 340 ⟶ 531:
v = v * x + coeffs(i%)
NEXT
= v</
=={{header|Bracmat}}==
<
= accumulator coefficients x coeff
. !arg:(?coefficients.?x)
Line 354 ⟶ 545:
)
& Horner$(-19 7 -4 6.3)
);</
Output:
<pre>128</pre>
Line 360 ⟶ 551:
=={{header|C}}==
{{trans|Fortran}}
<
double horner(double *coeffs, int s, double x)
Line 381 ⟶ 572:
printf("%5.1f\n", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0));
return 0;
}</
=={{header|C sharp|C#}}==
<
using System.Linq;
Line 399 ⟶ 590:
Console.WriteLine(Horner(new[] { -19.0, 7.0, -4.0, 6.0 }, 3.0));
}
}</
Output:
<pre>128</pre>
Line 406 ⟶ 597:
The same C function works too, but another solution could be:
<
#include <vector>
Line 426 ⟶ 617:
cout << horner(v, 3.0) << endl;
return 0;
}</
Yet another solution, which is more idiomatic in C++ and works on any bidirectional sequence:
<
#include <iostream>
Line 447 ⟶ 638:
std::cout << horner(c, c + 4, 3) << std::endl;
}
</syntaxhighlight>
=={{header|Clojure}}==
<
(reduce #(-> %1 (* x) (+ %2)) (reverse coeffs)))
(println (horner [-19 7 -4 6] 3))</
=={{header|CoffeeScript}}==
<
eval_poly = (x, coefficients) ->
# coefficients are for ascending powers
Line 466 ⟶ 657:
console.log eval_poly 10, [4, 3, 2, 1] # 1234
console.log eval_poly 2, [1, 1, 0, 0, 1] # 19
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(reduce #'(lambda (coef acc) (+ (* acc x) coef))
coeffs :from-end t :initial-value 0))</
Alternate version using LOOP. Coefficients are passed in a vector.
<
(loop :with y = 0
:for i :from (1- (length a)) :downto 0
Line 481 ⟶ 672:
:finally (return y)))
(horner 1.414 #(-2 0 1))</
=={{header|D}}==
The poly() function of the standard library std.math module uses Horner's rule:
<
void main() {
import std.stdio, std.math;
Line 493 ⟶ 684:
poly(x,pp).writeln;
}
}</
Basic implementation:
<
CommonType!(U, V) horner(U, V)(U[] p, V x) pure nothrow @nogc {
Line 506 ⟶ 697:
void main() {
[-19, 7, -4, 6].horner(3.0).writeln;
}</
More functional style:
<
auto horner(T, U)(in T[] p, in U x) pure nothrow @nogc {
Line 516 ⟶ 707:
void main() {
[-19, 7, -4, 6].horner(3.0).writeln;
}</
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|Classes,SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
function EvaluatePolynomial(Args: array of double; X: double): double;
{Evaluate polynomial using Horner's rule }
var I: integer;
begin
Result:=0;
for I:=High(Args) downto 0 do
Result:=(Result * X ) + Args[I];
end;
function GetPolynomialStr(Args: array of double; VarName: string): string;
{Return a string display the polynomial in normal format}
{for example: 6.0 X^3 - 4.0 X^2 + 7.0 X - 19.0}
var I: integer;
begin
Result:='';
for I:=High(Args) downto 0 do
begin
if Args[I]>0 then
begin
if I<>High(Args) then Result:=Result+' + ';
end
else Result:=Result+' - ';
Result:=Result+FloatToStrF(Abs(Args[I]),ffFixed,18,1);
if I>0 then Result:=Result+' '+VarName;
if I>1 then Result:=Result+'^'+IntToStr(I);
end;
end;
procedure ShowHornerPoly(Memo: TMemo; Args: array of double; X: double);
{Evaluate polynomial, show formated polynomal and the result}
var R: double;
begin
R:=EvaluatePolynomial(Args,X);
Memo.Lines.Add(FloatToStrF(R,ffFixed, 18,1));
Memo.Lines.Add(GetPolynomialStr(Args,'X'));
end;
procedure DoHornerPoly(Memo: TMemo);
begin
ShowHornerPoly(Memo,[-19, 7, -4, 6],3)
end;
</syntaxhighlight>
{{out}}
<pre>
128.0
6.0 X^3 - 4.0 X^2 + 7.0 X - 19.0
</pre>
=={{header|E}}==
<
def indexing := (0..!coefficients.size()).descending()
return def hornerPolynomial(x) {
Line 529 ⟶ 779:
return acc
}
}</
<
# value: 128</
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
func horner coeffs[] x .
for i = len coeffs[] downto 1
res = res * x + coeffs[i]
.
return res
.
print horner [ -19 7 -4 6 ] 3
</syntaxhighlight>
{{out}}
<pre>
128
</pre>
=={{header|EchoLisp}}==
=== Functional version ===
<
(define (horner x poly)
(foldr (lambda (coeff acc) (+ coeff (* acc x))) 0 poly))
(horner 3 '(-19 7 -4 6)) → 128
</syntaxhighlight>
=== Library ===
<
(lib 'math)
Lib: math.lib loaded.
Line 550 ⟶ 816:
(poly->string 'x P) → 6x^3 -4x^2 +7x -19
(poly 3 P) → 128
</syntaxhighlight>
=={{header|EDSAC order code}}==
<
[Copyright <2021> <ERIK SARGSYAN>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
Line 615 ⟶ 881:
EZPF
</syntaxhighlight>
{{out}}
<pre>
Line 624 ⟶ 890:
{{trans|C#}}
ELENA 5.0 :
<
import system'routines;
Line 635 ⟶ 901:
{
console.printLine(horner(new real[]{-19.0r, 7.0r, -4.0r, 6.0r}, 3.0r))
}</
{{out}}
<pre>
Line 642 ⟶ 908:
=={{header|Elixir}}==
<
IO.puts horner.([-19,7,-4,6], 3)</
{{out}}
Line 653 ⟶ 919:
=={{header|Emacs Lisp}}==
{{trans|Common Lisp}}
<
(defun horner (coeffs x)
Line 659 ⟶ 925:
coeffs :from-end t :initial-value 0))
(horner '(-19 7 -4 6) 3)</
{{out}}
Line 666 ⟶ 932:
=={{header|Erlang}}==
<
horner(L,X) ->
lists:foldl(fun(C, Acc) -> X*Acc+C end,0, lists:reverse(L)).
t() ->
horner([-19,7,-4,6], 3).
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM HORNER
Line 696 ⟶ 962:
PRINT(RES)
END PROGRAM
</syntaxhighlight>
=={{header|Euler Math Toolbox}}==
<syntaxhighlight lang="euler math toolbox">
>function horner (x,v) ...
$ n=cols(v); res=v{n};
Line 719 ⟶ 985:
3 2
6 x - 4 x + 7 x - 19
</syntaxhighlight>
=={{header|F Sharp|F#}}==
<
let horner l x =
List.rev l |> List.fold ( fun acc c -> x*acc+c) 0
horner [-19;7;-4;6] 3
</syntaxhighlight>
=={{header|Factor}}==
<
[ <reversed> 0 ] dip '[ [ _ * ] dip + ] reduce ;</
( scratchpad ) { -19 7 -4 6 } 3 horner .
Line 737 ⟶ 1,004:
=={{header|Forth}}==
<
0e
floats bounds ?do
Line 746 ⟶ 1,013:
create coeffs 6e f, -4e f, 7e f, -19e f,
coeffs 4 3e fhorner f. \ 128.</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
implicit none
Line 773 ⟶ 1,040:
end function horner
end program test_horner</
Output:
<pre>128.0</pre>
=== Fortran 77 ===
<
IMPLICIT NONE
INTEGER I,N
Line 787 ⟶ 1,054:
END DO
HORNER=Y
END</
As a matter of fact, computing the derivative is not much more difficult (see [http://www.cs.berkeley.edu/~wkahan/Math128/Poly.pdf Roundoff in Polynomial Evaluation], W. Kahan, 1986). The following subroutine computes both polynomial value and derivative for argument x.
<
C COMPUTE POLYNOMIAL VALUE AND DERIVATIVE
C SEE "ROUNDOFF IN POLYNOMIAL EVALUATION", W. KAHAN, 1986
Line 805 ⟶ 1,072:
10 Y = Y*X + A(I)
END
</syntaxhighlight>
=={{header|FreeBASIC}}==
<
Function AlgoritmoHorner(coeffs() As Integer, x As Integer) As Integer
Dim As Integer i, acumulador = 0
Line 822 ⟶ 1,089:
Print AlgoritmoHorner(coeficientes(), x)
End
</syntaxhighlight>
{{out}}
<pre>
Line 830 ⟶ 1,097:
=={{header|FunL}}==
{{trans|Haskell}}
<
def horner( poly, x ) = foldr( \a, b -> a + b*x, 0, poly )
println( horner([-19, 7, -4, 6], 3) )</
{{out}}
Line 840 ⟶ 1,107:
<pre>
128
</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">include "NSLog.incl"
local fn horner( coeffs as CFArrayRef, x as NSInteger ) as double
CFArrayRef reversedCoeffs
CFNumberRef num
double accumulator = 0.0
// Reverse coeffs array
reversedCoeffs = fn EnumeratorAllObjects( fn ArrayReverseObjectEnumerator( coeffs ) )
// Iterate over CFNumberRefs in reversed array, convert to double values, calculate and add to accumulator
for num in reversedCoeffs
accumulator = ( accumulator * x ) + fn NumberDoubleValue( num )
next
end fn = accumulator
CFArrayRef coeffs
coeffs = @[@-19.0, @7.0, @-4.0, @6.0]
NSLog( @"%7.1f", fn horner( coeffs, 3 ) )
coeffs = @[@4.0, @3.0, @2.0, @1.0]
NSLog( @"%7.1f", fn horner( coeffs, 10 ) )
coeffs = @[@1, @1, @0, @0, @1]
NSLog( @"%7.1f", fn horner( coeffs, 2 ) )
coeffs = @[@1.2, @2.3, @3.4, @4.5, @5.6]
NSLog( @"%7.1f", fn horner( coeffs, 8 ) )
coeffs = @[@1, @0, @1, @1, @1, @0, @0, @1]
NSLog( @"%7.1f", fn horner( coeffs, 2 ) )
HandleEvents</syntaxhighlight>
{{out}}
<pre>
128.0
1234.0
19.0
25478.8
157.0
</pre>
=={{header|GAP}}==
<
x := Indeterminate(Rationals, "x");
Line 874 ⟶ 1,187:
Horner(u, 3);
# 128</
=={{header|Go}}==
<
import "fmt"
Line 890 ⟶ 1,203:
func main() {
fmt.Println(horner(3, []int64{-19, 7, -4, 6}))
}</
Output:
<pre>
Line 898 ⟶ 1,211:
=={{header|Groovy}}==
Solution:
<
Test includes demonstration of [[currying]] to create polynomial functions of one variable from generic Horner's rule calculation. Also demonstrates constructing the derivative function for the given polynomial. And finally demonstrates in the Newton-Raphson method to find one of the polynomial's roots using the polynomial and derivative functions constructed earlier.
<
println (["p coefficients":coefficients])
Line 923 ⟶ 1,236:
def root = newtonRaphson(3g, testPoly, testDeriv)
println ([root:root.toString()[0..5], "p(root)":testPoly(root).toString()[0..5], "p'(root)":testDeriv(root).toString()[0..5]])</
Output:
Line 935 ⟶ 1,248:
=={{header|Haskell}}==
<
horner x = foldr (\a b -> a + b*x) 0
main = print $ horner 3 [-19, 7, -4, 6]</
=={{header|HicEst}}==
<
DATA coeffs/-19.0, 7.0, -4.0, 6.0/
Line 952 ⟶ 1,265:
Horner = x*Horner + c(i)
ENDDO
END</
=={{header|Icon}} and {{header|Unicon}}==
<syntaxhighlight lang="icon">
procedure poly_eval (x, coeffs)
accumulator := 0
Line 967 ⟶ 1,280:
write (poly_eval (3, [-19, 7, -4, 6]))
end
</syntaxhighlight>
=={{header|J}}==
'''Solution''':<
horner =: (#."0 _ |.)~ NB. Tacit
horner =: [: +`*/ [: }: ,@,. NB. Alternate tacit (equivalent)
horner =: 4 : ' (+ *&y)/x' NB. Alternate explicit (equivalent)
</syntaxhighlight>
'''Example''':<
128</
'''Note:'''<br>
The primitive verb <code>p.</code> would normally be used to evaluate polynomials.
<
128</
=={{header|Java}}==
{{works with|Java|1.5+}}
<
import java.util.Collections;
import java.util.List;
Line 1,006 ⟶ 1,319:
return accumulator;
}
}</
Output:
<pre>128.0</pre>
Line 1,014 ⟶ 1,327:
{{trans|Haskell}}
<
return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0);
}
console.log(horner([-19,7,-4,6],3)); // ==> 128
</syntaxhighlight>
=={{header|jq}}==
<syntaxhighlight lang=jq>
# Input: an array of coefficients specifying the polynomial
# to be evaluated at $x, where .[0] is the constant
def horner($x):
. as $coefficients
| reduce range(length-1; -1; -1) as $i (0; . * $x + $coefficients[$i]);
# Example
[-19, 7, -4, 6] | horner(3)
</syntaxhighlight>
'''Invocation''': $JQ -n -f horner.jq
where $JQ is either jq or gojq
{{output}}
<pre>
128
</pre>
=={{header|Julia}}==
Line 1,024 ⟶ 1,358:
'''Imperative''':
<
s = coefs[end] * one(x)
for k in length(coefs)-1:-1:1
Line 1,032 ⟶ 1,366:
end
@show horner([-19, 7, -4, 6], 3)</
{{out}}
Line 1,038 ⟶ 1,372:
'''Functional''':
<
@show horner2([-19, 7, -4, 6], 3)</
{{out}}
Line 1,047 ⟶ 1,381:
'''Note''':
In Julia 1.4 or later one would normally use the built-in '''evalpoly''' function for this purpose:
<
@show evalpoly(3, [-19, 7, -4, 6]) </
{{out}}
Line 1,054 ⟶ 1,388:
=={{header|K}}==
<syntaxhighlight lang="k">
horner:{y _sv|x}
horner[-19 7 -4 6;3]
128
</syntaxhighlight>
=={{header|Kotlin}}==
<
fun horner(coeffs: DoubleArray, x: Double): Double {
Line 1,072 ⟶ 1,406:
val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0)
println(horner(coeffs, 3.0))
}</
{{out}}
Line 1,080 ⟶ 1,414:
=={{header|Lambdatalk}}==
<
{def horner
{def horner.r
Line 1,097 ⟶ 1,431:
-> 2.220446049250313e-16 ~ 0
</syntaxhighlight>
=={{header|Liberty BASIC}}==
<
coefficients$ = "-19 7 -4 6" ' list coefficients of all x^0..x^n in order
x = 3
Line 1,119 ⟶ 1,453:
horner = accumulator
end function
</
=={{header|Logo}}==
<
if empty? :coeffs [output 0]
output (first :coeffs) + (:x * horner :x bf :coeffs)
end
show horner 3 [-19 7 -4 6] ; 128</
=={{header|Lua}}==
<
local res = 0
for i = #coeff, 1, -1 do
Line 1,140 ⟶ 1,474:
x = 3
coefficients = { -19, 7, -4, 6 }
print( horners_rule( coefficients, x ) )</
=={{header|Maple}}==
<syntaxhighlight lang="maple">
applyhorner:=(L::list,x)->foldl((s,t)->s*x+t,op(ListTools:-Reverse(L))):
Line 1,149 ⟶ 1,483:
applyhorner([-19,7,-4,6],3);
</syntaxhighlight>
Output:
<pre>
Line 1,158 ⟶ 1,492:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Horner[{6, -4, 7, -19}, x]
-> -19 + x (7 + x (-4 + 6 x))
-19 + x (7 + x (-4 + 6 x)) /. x -> 3
-> 128</
=={{header|MATLAB}}==
<
accumulator = 0;
Line 1,174 ⟶ 1,508:
end
end</
Output:
<
ans =
128</
Matlab also has a built-in function "polyval" which uses Horner's Method to evaluate polynomials. The list of coefficients is in descending order of power, where as to task spec specifies ascending order.
<
ans =
128</
=={{header|Maxima}}==
<
horner(5*x^3+2*x+1);
x*(5*x^2+2)+1
Line 1,233 ⟶ 1,567:
poleval([0, 0, 0, 0, 1], x);
x^4</
=={{header|Mercury}}==
<
:- module horner.
:- interface.
Line 1,250 ⟶ 1,584:
horner(X, Cs) = list.foldr((func(C, Acc) = Acc * X + C), Cs, 0).
</syntaxhighlight>
=={{header|МК-61/52}}==
<syntaxhighlight lang="text">ИП0 1 + П0
ИПE ИПD * КИП0 + ПE
ИП0 1 - x=0 04
ИПE С/П</
''Input:'' Р1:РС - coefficients, Р0 - number of the coefficients, РD - ''x''.
=={{header|Modula-2}}==
<
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 1,289 ⟶ 1,623:
WriteLn;
ReadChar
END Horner.</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols nobinary
Line 1,303 ⟶ 1,637:
End
Say r
Say 6*x**3-4*x**2+7*x-19</
'''Output:'''
<pre>128
Line 1,309 ⟶ 1,643:
=={{header|Nim}}==
<
iterator reversed[T](x: openArray[T]): T =
for i in countdown(x.high, x.low):
Line 1,318 ⟶ 1,652:
result = result * x + c
echo horner([-19, 7, -4, 6], 3)</
=={{header|Oberon-2}}==
{{works with|oo2c}}
<
MODULE HornerRule;
IMPORT
Line 1,351 ⟶ 1,685:
Out.Int(Eval(coefs^,4,3),0);Out.Ln
END HornerRule.
</syntaxhighlight>
{{out}}
<pre>
Line 1,358 ⟶ 1,692:
=={{header|Objeck}}==
<
class Horner {
function : Main(args : String[]) ~ Nil {
Line 1,378 ⟶ 1,712:
}
}
</syntaxhighlight>
=={{header|Objective-C}}==
{{works with|Mac OS X|10.6+}} Using blocks
<
typedef double (^mfunc)(double, double);
Line 1,423 ⟶ 1,757:
}
return 0;
}</
=={{header|OCaml}}==
<
List.fold_left (fun acc coef -> acc * x + coef) 0 (List.rev coeffs) ;;
val horner : int list -> int -> int = <fun>
Line 1,433 ⟶ 1,767:
# let coeffs = [-19; 7; -4; 6] in
horner coeffs 3 ;;
- : int = 128</
It's also possible to do fold_right instead of reversing and doing fold_left; but fold_right is not tail-recursive.
=={{header|Octave}}==
<
r = 0.0;
for i = length(a):-1:1
Line 1,444 ⟶ 1,778:
endfunction
horner([-19, 7, -4, 6], 3)</
=={{header|ooRexx}}==
<
* 04.03.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 1,458 ⟶ 1,792:
End
Say r
Say 6*x**3-4*x**2+7*x-19</
'''Output:'''
<pre>128
Line 1,464 ⟶ 1,798:
=={{header|Oz}}==
<
fun {Horner Coeffs X}
{FoldL1 {Reverse Coeffs}
Line 1,476 ⟶ 1,810:
end
in
{Show {Horner [~19 7 ~4 6] 3}}</
=={{header|PARI/GP}}==
Also note that Pari has a polynomial type. Evaluating these is as simple as <code>subst(P,variable(P),x)</code>.
<
my(s=0);
forstep(i=#v,1,-1,s=s*x+v[i]);
s
};</
=={{header|Pascal}}==
<
function horner(a: array of double; x: double): double;
Line 1,504 ⟶ 1,838:
write ('Horner calculated polynomial of 6*x^3 - 4*x^2 + 7*x - 19 for x = 3: ');
writeln (horner (poly, 3.0):8:4);
end.</
Output:
<pre>Horner calculated polynomial of 6*x^3 - 4*x^2 + 7*x - 19 for x = 3: 128.0000
Line 1,510 ⟶ 1,844:
=={{header|Perl}}==
<
use strict;
use warnings;
Line 1,523 ⟶ 1,857:
my @coeff = (-19.0, 7, -4, 6);
my $x = 3;
say horner @coeff, $x;</
===<!-- Perl -->Functional version===
<
use List::Util qw(reduce);
Line 1,536 ⟶ 1,870:
my @coeff = (-19.0, 7, -4, 6);
my $x = 3;
print horner(\@coeff, $x), "\n";</
===<!-- Perl -->Recursive version===
<
my ($coeff, $x) = @_;
@$coeff and
Line 1,545 ⟶ 1,879:
}
print horner( [ -19, 7, -4, 6 ], 3 );</
=={{header|Phix}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">horner</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">coeff</span><span style="color: #0000FF;">)</span>
Line 1,559 ⟶ 1,893:
<span style="color: #0000FF;">?</span><span style="color: #000000;">horner</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,{-</span><span style="color: #000000;">19</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">})</span>
<!--</
{{out}}
<pre>
Line 1,566 ⟶ 1,900:
=={{header|PHP}}==
<
function horner($coeff, $x) {
$result = 0;
Line 1,577 ⟶ 1,911:
$x = 3;
echo horner($coeff, $x), "\n";
?></
===Functional version===
{{works with|PHP|5.3+}}
<
function horner($coeff, $x) {
return array_reduce(array_reverse($coeff), function ($a, $b) use ($x) { return $a * $x + $b; }, 0);
Line 1,589 ⟶ 1,923:
$x = 3;
echo horner($coeff, $x), "\n";
?></
=={{header|Picat}}==
===Recursion===
<
horner([H|T],X,V) :-
horner(T,X,V1),
V = V1 * X + H.</
===Iterative===
<
Acc = 0,
foreach(I in Coeff.length..-1..1)
Acc := Acc*X + Coeff[I]
end,
V = Acc.</
===Functional approach===
<
horner3(Coeff, X) = fold($h3(X),0,Coeff.reverse()).</
===Test===
<
horner([-19, 7, -4, 6], 3, V),
println(V),
Line 1,620 ⟶ 1,954:
V3 = horner3([-19, 7, -4, 6], 3),
println(V3),
nl.</
{{out}}
Line 1,628 ⟶ 1,962:
=={{header|PicoLisp}}==
<
(let Res 0
(for C (reverse Coeffs)
(setq Res (+ C (* X Res))) ) ) )</
<
-> 128</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
declare (i, n) fixed binary, (x, value) float; /* 11 May 2010 */
get (x);
Line 1,649 ⟶ 1,983:
put (value);
end;
</syntaxhighlight>
=={{header|Potion}}==
<
result = 0
coef reverse each (a) :
Line 1,660 ⟶ 1,994:
.
horner(3, (-19, 7, -4, 6)) print</
=={{header|PowerShell}}==
{{works with|PowerShell|4.0}}
<syntaxhighlight lang="powershell">
function horner($coefficients, $x) {
$accumulator = 0
Line 1,675 ⟶ 2,009:
$x = 3
horner $coefficients $x
</syntaxhighlight>
<b>Output:</b>
<pre>
Line 1,683 ⟶ 2,017:
=={{header|Prolog}}==
Tested with SWI-Prolog. Works with other dialects.
<
horner([H|T], X, V) :-
horner(T, X, V1),
V is V1 * X + H.
</syntaxhighlight>
Output :
<
V = 128.</
===Functional approach===
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
<
Line 1,707 ⟶ 2,041:
f_horner(L, V, R) :-
foldr(\X^Y^Z^(Z is X * V + Y), 0, L, R).
</syntaxhighlight>
===Functional syntax (Ciao)===
Works with Ciao (https://github.com/ciao-lang/ciao) and the fsyntax package:
<syntaxhighlight lang="prolog">
:- module(_, [horner/3], [fsyntax, hiord]).
:- use_module(library(hiordlib)).
horner(L, X) := ~foldr((''(H,V0,V) :- V is V0*X + H), L, 0).
</syntaxhighlight>
=={{header|PureBasic}}==
<
Define result
ForEach Coefficients()
Line 1,724 ⟶ 2,058:
Next
ProcedureReturn result
EndProcedure</
'''Implemented as
<
AddElement(a()): a()= 6
AddElement(a()): a()= -4
AddElement(a()): a()= 7
AddElement(a()): a()=-19
Debug Horner(a(),3)</
'''Outputs
128
=={{header|Python}}==
<
acc = 0
for c in reversed(coeffs):
Line 1,744 ⟶ 2,078:
>>> horner( (-19, 7, -4, 6), 3)
128</
===Functional version===
<
except: pass
Line 1,754 ⟶ 2,088:
>>> horner( (-19, 7, -4, 6), 3)
128</
==={{libheader|NumPy}}===
<
>>> numpy.polynomial.polynomial.polyval(3, (-19, 7, -4, 6))
128.0</
=={{header|R}}==
Procedural style:
<
y <- 0
for(c in rev(a)) {
Line 1,771 ⟶ 2,105:
}
cat(horner(c(-19, 7, -4, 6), 3), "\n")</
Functional style:
<
Reduce(v, right=T, f=function(a, b) {
b * x + a
})
}</
{{out}}
<pre>
Line 1,788 ⟶ 2,122:
Translated from Haskell
<
#lang racket
(define (horner x l)
Line 1,795 ⟶ 2,129:
(horner 3 '(-19 7 -4 6))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
@coeffs.reverse.reduce: { $^a * $x + $^b };
}
say horner( [ -19, 7, -4, 6 ], 3 );</
A recursive version would spare us the need for reversing the list of coefficients. However, special care must be taken in order to write it, because the way Raku implements lists is not optimized for this kind of treatment. [[Lisp]]-style lists are, and fortunately it is possible to emulate them with [http://doc.raku.org/type/Pair Pairs] and the reduction meta-operator:
<syntaxhighlight lang="raku"
multi horner(Pair $c, $x) {
$c.key + $x * horner( $c.value, $x )
}
say horner( [=>](-19, 7, -4, 6 ), 3 );</
We can also use the composition operator:
<syntaxhighlight lang="raku"
([o] map { $_ + $x * * }, @coeffs)(0);
}
say horner( [ -19, 7, -4, 6 ], 3 );</
{{out}}
Line 1,825 ⟶ 2,159:
One advantage of using the composition operator is that it allows for the use of an infinite list of coefficients.
<syntaxhighlight lang="raku"
map { .(0) }, [\o] map { $_ + $x * * }, @coeffs;
}
say horner( [ 1 X/ (1, |[\*] 1 .. *) ], i*pi )[20];
</syntaxhighlight>
{{out}}
<pre>-0.999999999924349-5.28918515954219e-10i</pre>
=={{header|Rascal}}==
<
public int horners_rule(list[int] coefficients, int x){
Line 1,842 ⟶ 2,176:
acc = acc * x + i;}
return acc;
}</
A neater and shorter solution using a reducer:
<
Output:
<
int: 128
rascal>horners_rule2([-19, 7, -4, 6], 3)
int: 128</
=={{header|REBOL}}==
<
horner: func [coeffs x] [
Line 1,864 ⟶ 2,198:
]
print horner [-19 7 -4 6] 3</
=={{header|REXX}}==
===version 1===
<
numeric digits 30 /*use extra numeric precision. */
parse arg x poly /*get value of X and the coefficients. */
Line 1,886 ⟶ 2,220:
end /*j*/
say /*display a blank line for readability.*/
say ' answer = ' a /*stick a fork in it, we're all done. */</
'''output''' when the following is used for input: <tt> 3 -19 7 -4 6 </tt>
<pre>
Line 1,897 ⟶ 2,231:
===version 2===
<
* 27.07.2012 Walter Pachl
* coefficients reversed to descending order of power
Line 1,941 ⟶ 2,275:
Say ' equation = ' equ
Say ' '
Say ' result = ' a</
{{out}}
<pre> x = 3
Line 1,950 ⟶ 2,284:
=={{header|Ring}}==
<
coefficients = [-19, 7, -4, 6]
see "x = 3" + nl +
Line 1,963 ⟶ 2,297:
next
return w
</syntaxhighlight>
Output:
<pre>
Line 1,979 ⟶ 2,313:
This said, solution to the problem is
<syntaxhighlight lang="rlab">
>> a = [6, -4, 7, -19]
6 -4 7 -19
Line 1,987 ⟶ 2,321:
128
</syntaxhighlight>
=={{header|RPL}}==
===Translation of the algorithm===
Following the pseudocode given [https://web.physics.utah.edu/~detar/lessons/c++/array/node2.html here] to the letter:
≪ OVER DUP SIZE GET → a x0 p
≪ a SIZE 1 - 1 '''FOR''' j
'a(j)+x0*p' EVAL 'p' STO -1 '''STEP'''
p
≫ ≫ ‘'''HORNR'''’ STO
===Idiomatic one-liner===
Reducing the loop to its simplest form: one memory call, one multiplication and one addition.
≪ → x0 ≪ LIST→ 2 SWAP '''START''' x0 * + '''NEXT''' ≫ ≫ ‘'''HORNR'''’ STO
{{in}}
<pre>
{ -19 7 -4 6 } 3 HORNR
</pre>
{{out}}
<pre>
1: 128
</pre>
=={{header|Ruby}}==
<
coeffs.reverse.inject(0) {|acc, coeff| acc * x + coeff}
end
p horner([-19, 7, -4, 6], 3) # ==> 128</
=={{header|Run BASIC}}==
<
x = 3
print horner(coef$,x) '128
Line 2,012 ⟶ 2,367:
next
horner = accum
end function</
=={{header|Rust}}==
<
v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff)
}
Line 2,022 ⟶ 2,377:
let v = [-19., 7., -4., 6.];
println!("result: {}", horner(&v, 3.0));
}</
A generic version that works with any number type and much more. So much more, it's hard to imagine what that may be useful for.
<
use num::Zero;
use std::ops::{Add, Mul};
Line 2,044 ⟶ 2,399:
let output: f64 = horner(&v, 3.0);
println!("result: {}", output);
}</
=={{header|Sather}}==
<
action(s, e, x:FLT):FLT is
Line 2,061 ⟶ 2,416:
#OUT + horner(|-19.0, 7.0, -4.0, 6.0|, 3.0) + "\n";
end;
end;</
=={{header|Scala}}==
<
coeffs.reverse.foldLeft(0.0){(a,c)=> a*x+c}
</syntaxhighlight>
<
println(horner(coeffs, 3))
-> 128.0
</syntaxhighlight>
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(define (*horner lst x acc)
(if (null? lst)
Line 2,082 ⟶ 2,437:
(display (horner (list -19 7 -4 6) 3))
(newline)</
Output:
<syntaxhighlight lang="text">128</
=={{header|Seed7}}==
<
include "float.s7i";
Line 2,108 ⟶ 2,463:
begin
writeln(horner(coeffs, 3.0) digits 1);
end func;</
Output:
Line 2,117 ⟶ 2,472:
=={{header|Sidef}}==
Functional:
<
coeff.reverse.reduce { |a,b| a*x + b };
}
say horner([-19, 7, -4, 6], 3); # => 128</
Recursive:
<
(coeff.len > 0) \
: 0
}
say horner([-19, 7, -4, 6], 3)
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
horner: aValue [
^ self reverse inject: 0 into: [:acc :c | acc * aValue + c].
Line 2,139 ⟶ 2,495:
].
(#(-19 7 -4 6) asOrderedCollection horner: 3) displayNl.</
=={{header|Standard ML}}==
<
fun horner coeffList x = foldr (fn (a, b) => a + b * x) (0.0) coeffList</
=={{header|Swift}}==
<
return reduce(lazy(coefs).reverse(), 0) { $0 * x + $1 }
}
println(horner([-19, 7, -4, 6], 3))</
{{out}}
<pre>128.0</pre>
=={{header|Tcl}}==
<
proc horner {coeffs x} {
set y 0
Line 2,162 ⟶ 2,518:
}
return $y
}</
Demonstrating:
<
Output:
<pre>128</pre>
Line 2,172 ⟶ 2,528:
Note: this function, "Horner", gets its coefficients as a ParamArray which has no specified length. This array collect all arguments after the first one(s). This means you must specify x first, then the coefficients.
<syntaxhighlight lang="vba">
Public Function Horner(x, ParamArray coeff())
Dim result As Double
Line 2,185 ⟶ 2,541:
Horner = result
End Function
</syntaxhighlight>
Output:
Line 2,194 ⟶ 2,550:
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
Function horners_rule(coefficients,x)
accumulator = 0
Line 2,204 ⟶ 2,560:
WScript.StdOut.WriteLine horners_rule(Array(-19,7,-4,6),3)
</syntaxhighlight>
{{Out}}
Line 2,211 ⟶ 2,567:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Function Horner(coefficients As Double(), variable As Double) As Double
Line 2,221 ⟶ 2,577:
End Sub
End Module</
{{out}}
<pre>128</pre>
Line 2,227 ⟶ 2,583:
=={{header|Visual FoxPro}}==
===Coefficients in ascending order.===
<
LOCAL x As Double
LOCAL ARRAY aCoeffs[1]
Line 2,247 ⟶ 2,603:
RETURN s
ENDFUNC
</syntaxhighlight>
===Coefficients in descending order.===
<
LOCAL x As Double
LOCAL ARRAY aCoeffs[1]
Line 2,269 ⟶ 2,625:
RETURN s
ENDFUNC
</syntaxhighlight>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn horner(x i64, c []i64) i64 {
mut acc := i64(0)
for i := c.len - 1; i >= 0; i-- {
Line 2,282 ⟶ 2,638:
fn main() {
println(horner(3, [i64(-19), 7, -4, 6]))
}</
{{out}}
Line 2,290 ⟶ 2,646:
=={{header|Wren}}==
<
var count = c.count
if (count == 0) return 0
Line 2,296 ⟶ 2,652:
}
System.print(horner.call(3, [-19, 7, -4, 6]))</
{{out}}
Line 2,304 ⟶ 2,660:
=={{header|XPL0}}==
<
func Horner(X, N, C); \Return value of polynomial in X
Line 2,315 ⟶ 2,671:
];
IntOut(0, Horner(3, 4, [-19, 7, -4, 6]));</
Output:
Line 2,323 ⟶ 2,679:
=={{header|zkl}}==
<
{ coeffs.reverse().reduce('wrap(a,coeff){ a*x + coeff },0.0) }</
{{out}}
<pre>
|