Horner's rule for polynomial evaluation: Difference between revisions
Content added Content deleted
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 24: | Line 24: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F horner(coeffs, x) |
||
V acc = 0 |
V acc = 0 |
||
L(c) reversed(coeffs) |
L(c) reversed(coeffs) |
||
Line 30: | Line 30: | ||
R acc |
R acc |
||
print(horner([-19, 7, -4, 6], 3))</ |
print(horner([-19, 7, -4, 6], 3))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 38: | Line 38: | ||
=={{header|360 Assembly}}== |
=={{header|360 Assembly}}== |
||
< |
<syntaxhighlight lang="360asm">* Horner's rule for polynomial evaluation - 07/10/2015 |
||
HORNER CSECT |
HORNER CSECT |
||
USING HORNER,R15 set base register |
USING HORNER,R15 set base register |
||
Line 58: | Line 58: | ||
PG DS CL12 buffer |
PG DS CL12 buffer |
||
YREGS |
YREGS |
||
END HORNER</ |
END HORNER</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 65: | Line 65: | ||
=={{header|ACL2}}== |
=={{header|ACL2}}== |
||
< |
<syntaxhighlight lang="lisp">(defun horner (ps x) |
||
(if (endp ps) |
(if (endp ps) |
||
0 |
0 |
||
(+ (first ps) |
(+ (first ps) |
||
(* x (horner (rest ps) x)))))</ |
(* x (horner (rest ps) x)))))</syntaxhighlight> |
||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">INT FUNC Horner(INT ARRAY coeffs INT count,x) |
||
INT v,i |
INT v,i |
||
Line 102: | Line 102: | ||
res=Horner(coeffs,4,x) |
res=Horner(coeffs,4,x) |
||
PrintF("=%I%E",res) |
PrintF("=%I%E",res) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Horner's_rule_for_polynomial_evaluation.png Screenshot from Atari 8-bit computer] |
[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: | Line 111: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Float_Text_IO; use Ada.Float_Text_IO; |
||
procedure Horners_Rule is |
procedure Horners_Rule is |
||
Line 127: | Line 127: | ||
begin |
begin |
||
Put(Horner(Coeffs => (-19.0, 7.0, -4.0, 6.0), Val => 3.0), Aft=>1, Exp=>0); |
Put(Horner(Coeffs => (-19.0, 7.0, -4.0, 6.0), Val => 3.0), Aft=>1, Exp=>0); |
||
end Horners_Rule;</ |
end Horners_Rule;</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>128.0</pre> |
<pre>128.0</pre> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">real |
||
horner(list coeffs, real x) |
horner(list coeffs, real x) |
||
{ |
{ |
||
Line 154: | Line 154: | ||
0; |
0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
{{works with|ALGOL 68G}} |
{{works with|ALGOL 68G}} |
||
< |
<syntaxhighlight lang="algol68">PROC horner = ([]REAL c, REAL x)REAL : |
||
( |
( |
||
REAL res := 0.0; |
REAL res := 0.0; |
||
Line 170: | Line 170: | ||
[4]REAL coeffs := (-19.0, 7.0, -4.0, 6.0); |
[4]REAL coeffs := (-19.0, 7.0, -4.0, 6.0); |
||
print( horner(coeffs, 3.0) ) |
print( horner(coeffs, 3.0) ) |
||
)</ |
)</syntaxhighlight> |
||
=={{header|ALGOL W}}== |
=={{header|ALGOL W}}== |
||
< |
<syntaxhighlight lang="algolw">begin |
||
% Horner's rule for polynominal evaluation % |
% Horner's rule for polynominal evaluation % |
||
% returns the value of the polynominal defined by coefficients, % |
% returns the value of the polynominal defined by coefficients, % |
||
Line 199: | Line 199: | ||
write( r_format := "A", r_w := 8, r_d := 2, Horner( coefficients, 4, 3 ) ) |
write( r_format := "A", r_w := 8, r_d := 2, Horner( coefficients, 4, 3 ) ) |
||
end test_cases |
end test_cases |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 207: | Line 207: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
Works in [[Dyalog APL]] |
Works in [[Dyalog APL]] |
||
<lang |
<syntaxhighlight lang="apl">h←⊥∘⌽</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
<pre> |
<pre> |
||
Line 215: | Line 215: | ||
=={{header|ATS}}== |
=={{header|ATS}}== |
||
< |
<syntaxhighlight lang="ats">#include |
||
"share/atspre_staload.hats" |
"share/atspre_staload.hats" |
||
Line 238: | Line 238: | ||
in |
in |
||
println! (res) |
println! (res) |
||
end // end of [main0]</ |
end // end of [main0]</syntaxhighlight> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">horner: function [coeffs, x][ |
||
result: 0 |
result: 0 |
||
loop reverse coeffs 'c -> |
loop reverse coeffs 'c -> |
||
Line 249: | Line 249: | ||
] |
] |
||
print horner @[neg 19, 7, neg 4, 6] 3</ |
print horner @[neg 19, 7, neg 4, 6] 3</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 256: | Line 256: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">Coefficients = -19, 7, -4, 6 |
||
x := 3 |
x := 3 |
||
Line 271: | Line 271: | ||
i := Co0 - A_Index + 1, Result := Result * x + Co%i% |
i := Co0 - A_Index + 1, Result := Result * x + Co%i% |
||
Return, Result |
Return, Result |
||
}</ |
}</syntaxhighlight> |
||
Message box shows: |
Message box shows: |
||
<pre>128</pre> |
<pre>128</pre> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">#!/usr/bin/awk -f |
||
function horner(x, A) { |
function horner(x, A) { |
||
acc = 0; |
acc = 0; |
||
Line 287: | Line 287: | ||
split(p,P); |
split(p,P); |
||
print horner(x,P); |
print horner(x,P); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 296: | Line 296: | ||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
Line 320: | Line 320: | ||
echo %return% |
echo %return% |
||
exit /b |
exit /b |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 330: | Line 330: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM coefficients(3) |
||
coefficients() = -19, 7, -4, 6 |
coefficients() = -19, 7, -4, 6 |
||
PRINT FNhorner(coefficients(), 3) |
PRINT FNhorner(coefficients(), 3) |
||
Line 340: | Line 340: | ||
v = v * x + coeffs(i%) |
v = v * x + coeffs(i%) |
||
NEXT |
NEXT |
||
= v</ |
= v</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat">( ( Horner |
||
= accumulator coefficients x coeff |
= accumulator coefficients x coeff |
||
. !arg:(?coefficients.?x) |
. !arg:(?coefficients.?x) |
||
Line 354: | Line 354: | ||
) |
) |
||
& Horner$(-19 7 -4 6.3) |
& Horner$(-19 7 -4 6.3) |
||
);</ |
);</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>128</pre> |
<pre>128</pre> |
||
Line 360: | Line 360: | ||
=={{header|C}}== |
=={{header|C}}== |
||
{{trans|Fortran}} |
{{trans|Fortran}} |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
double horner(double *coeffs, int s, double x) |
double horner(double *coeffs, int s, double x) |
||
Line 381: | Line 381: | ||
printf("%5.1f\n", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0)); |
printf("%5.1f\n", horner(coeffs, sizeof(coeffs)/sizeof(double), 3.0)); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Linq; |
using System.Linq; |
||
Line 399: | Line 399: | ||
Console.WriteLine(Horner(new[] { -19.0, 7.0, -4.0, 6.0 }, 3.0)); |
Console.WriteLine(Horner(new[] { -19.0, 7.0, -4.0, 6.0 }, 3.0)); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>128</pre> |
<pre>128</pre> |
||
Line 406: | Line 406: | ||
The same C function works too, but another solution could be: |
The same C function works too, but another solution could be: |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <vector> |
#include <vector> |
||
Line 426: | Line 426: | ||
cout << horner(v, 3.0) << endl; |
cout << horner(v, 3.0) << endl; |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
Yet another solution, which is more idiomatic in C++ and works on any bidirectional sequence: |
Yet another solution, which is more idiomatic in C++ and works on any bidirectional sequence: |
||
< |
<syntaxhighlight lang="cpp"> |
||
#include <iostream> |
#include <iostream> |
||
Line 447: | Line 447: | ||
std::cout << horner(c, c + 4, 3) << std::endl; |
std::cout << horner(c, c + 4, 3) << std::endl; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(defn horner [coeffs x] |
||
(reduce #(-> %1 (* x) (+ %2)) (reverse coeffs))) |
(reduce #(-> %1 (* x) (+ %2)) (reverse coeffs))) |
||
(println (horner [-19 7 -4 6] 3))</ |
(println (horner [-19 7 -4 6] 3))</syntaxhighlight> |
||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript"> |
||
eval_poly = (x, coefficients) -> |
eval_poly = (x, coefficients) -> |
||
# coefficients are for ascending powers |
# coefficients are for ascending powers |
||
Line 466: | Line 466: | ||
console.log eval_poly 10, [4, 3, 2, 1] # 1234 |
console.log eval_poly 10, [4, 3, 2, 1] # 1234 |
||
console.log eval_poly 2, [1, 1, 0, 0, 1] # 19 |
console.log eval_poly 2, [1, 1, 0, 0, 1] # 19 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun horner (coeffs x) |
||
(reduce #'(lambda (coef acc) (+ (* acc x) coef)) |
(reduce #'(lambda (coef acc) (+ (* acc x) coef)) |
||
coeffs :from-end t :initial-value 0))</ |
coeffs :from-end t :initial-value 0))</syntaxhighlight> |
||
Alternate version using LOOP. Coefficients are passed in a vector. |
Alternate version using LOOP. Coefficients are passed in a vector. |
||
< |
<syntaxhighlight lang="lisp">(defun horner (x a) |
||
(loop :with y = 0 |
(loop :with y = 0 |
||
:for i :from (1- (length a)) :downto 0 |
:for i :from (1- (length a)) :downto 0 |
||
Line 481: | Line 481: | ||
:finally (return y))) |
:finally (return y))) |
||
(horner 1.414 #(-2 0 1))</ |
(horner 1.414 #(-2 0 1))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
The poly() function of the standard library std.math module uses Horner's rule: |
The poly() function of the standard library std.math module uses Horner's rule: |
||
< |
<syntaxhighlight lang="d">void main() { |
||
void main() { |
void main() { |
||
import std.stdio, std.math; |
import std.stdio, std.math; |
||
Line 493: | Line 493: | ||
poly(x,pp).writeln; |
poly(x,pp).writeln; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Basic implementation: |
Basic implementation: |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.traits; |
||
CommonType!(U, V) horner(U, V)(U[] p, V x) pure nothrow @nogc { |
CommonType!(U, V) horner(U, V)(U[] p, V x) pure nothrow @nogc { |
||
Line 506: | Line 506: | ||
void main() { |
void main() { |
||
[-19, 7, -4, 6].horner(3.0).writeln; |
[-19, 7, -4, 6].horner(3.0).writeln; |
||
}</ |
}</syntaxhighlight> |
||
More functional style: |
More functional style: |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range; |
||
auto horner(T, U)(in T[] p, in U x) pure nothrow @nogc { |
auto horner(T, U)(in T[] p, in U x) pure nothrow @nogc { |
||
Line 516: | Line 516: | ||
void main() { |
void main() { |
||
[-19, 7, -4, 6].horner(3.0).writeln; |
[-19, 7, -4, 6].horner(3.0).writeln; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def makeHornerPolynomial(coefficients :List) { |
||
def indexing := (0..!coefficients.size()).descending() |
def indexing := (0..!coefficients.size()).descending() |
||
return def hornerPolynomial(x) { |
return def hornerPolynomial(x) { |
||
Line 529: | Line 529: | ||
return acc |
return acc |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="e">? makeHornerPolynomial([-19, 7, -4, 6])(3) |
||
# value: 128</ |
# value: 128</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
=== Functional version === |
=== Functional version === |
||
< |
<syntaxhighlight lang="lisp"> |
||
(define (horner x poly) |
(define (horner x poly) |
||
(foldr (lambda (coeff acc) (+ coeff (* acc x))) 0 poly)) |
(foldr (lambda (coeff acc) (+ coeff (* acc x))) 0 poly)) |
||
(horner 3 '(-19 7 -4 6)) → 128 |
(horner 3 '(-19 7 -4 6)) → 128 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=== Library === |
=== Library === |
||
< |
<syntaxhighlight lang="lisp"> |
||
(lib 'math) |
(lib 'math) |
||
Lib: math.lib loaded. |
Lib: math.lib loaded. |
||
Line 550: | Line 550: | ||
(poly->string 'x P) → 6x^3 -4x^2 +7x -19 |
(poly->string 'x P) → 6x^3 -4x^2 +7x -19 |
||
(poly 3 P) → 128 |
(poly 3 P) → 128 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|EDSAC order code}}== |
=={{header|EDSAC order code}}== |
||
< |
<syntaxhighlight lang="edsac"> |
||
[Copyright <2021> <ERIK SARGSYAN> |
[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"), |
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), |
||
Line 615: | Line 615: | ||
EZPF |
EZPF |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 624: | Line 624: | ||
{{trans|C#}} |
{{trans|C#}} |
||
ELENA 5.0 : |
ELENA 5.0 : |
||
< |
<syntaxhighlight lang="elena">import extensions; |
||
import system'routines; |
import system'routines; |
||
Line 635: | Line 635: | ||
{ |
{ |
||
console.printLine(horner(new real[]{-19.0r, 7.0r, -4.0r, 6.0r}, 3.0r)) |
console.printLine(horner(new real[]{-19.0r, 7.0r, -4.0r, 6.0r}, 3.0r)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 642: | Line 642: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">horner = fn(list, x)-> List.foldr(list, 0, fn(c,acc)-> x*acc+c end) end |
||
IO.puts horner.([-19,7,-4,6], 3)</ |
IO.puts horner.([-19,7,-4,6], 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 653: | Line 653: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
{{trans|Common Lisp}} |
{{trans|Common Lisp}} |
||
< |
<syntaxhighlight lang="lisp">(require 'cl-lib) |
||
(defun horner (coeffs x) |
(defun horner (coeffs x) |
||
Line 659: | Line 659: | ||
coeffs :from-end t :initial-value 0)) |
coeffs :from-end t :initial-value 0)) |
||
(horner '(-19 7 -4 6) 3)</ |
(horner '(-19 7 -4 6) 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 666: | Line 666: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang"> |
||
horner(L,X) -> |
horner(L,X) -> |
||
lists:foldl(fun(C, Acc) -> X*Acc+C end,0, lists:reverse(L)). |
lists:foldl(fun(C, Acc) -> X*Acc+C end,0, lists:reverse(L)). |
||
t() -> |
t() -> |
||
horner([-19,7,-4,6], 3). |
horner([-19,7,-4,6], 3). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM HORNER |
PROGRAM HORNER |
||
Line 696: | Line 696: | ||
PRINT(RES) |
PRINT(RES) |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euler Math Toolbox}}== |
=={{header|Euler Math Toolbox}}== |
||
<syntaxhighlight lang="euler math toolbox"> |
|||
<lang Euler Math Toolbox> |
|||
>function horner (x,v) ... |
>function horner (x,v) ... |
||
$ n=cols(v); res=v{n}; |
$ n=cols(v); res=v{n}; |
||
Line 719: | Line 719: | ||
3 2 |
3 2 |
||
6 x - 4 x + 7 x - 19 |
6 x - 4 x + 7 x - 19 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
let horner l x = |
let horner l x = |
||
List.rev l |> List.fold ( fun acc c -> x*acc+c) 0 |
List.rev l |> List.fold ( fun acc c -> x*acc+c) 0 |
||
horner [-19;7;-4;6] 3 |
horner [-19;7;-4;6] 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">: horner ( coeff x -- res ) |
||
[ <reversed> 0 ] dip '[ [ _ * ] dip + ] reduce ;</ |
[ <reversed> 0 ] dip '[ [ _ * ] dip + ] reduce ;</syntaxhighlight> |
||
( scratchpad ) { -19 7 -4 6 } 3 horner . |
( scratchpad ) { -19 7 -4 6 } 3 horner . |
||
Line 737: | Line 737: | ||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: fhorner ( coeffs len F: x -- F: val ) |
||
0e |
0e |
||
floats bounds ?do |
floats bounds ?do |
||
Line 746: | Line 746: | ||
create coeffs 6e f, -4e f, 7e f, -19e f, |
create coeffs 6e f, -4e f, 7e f, -19e f, |
||
coeffs 4 3e fhorner f. \ 128.</ |
coeffs 4 3e fhorner f. \ 128.</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|90 and later}} |
{{works with|Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program test_horner |
||
implicit none |
implicit none |
||
Line 773: | Line 773: | ||
end function horner |
end function horner |
||
end program test_horner</ |
end program test_horner</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>128.0</pre> |
<pre>128.0</pre> |
||
=== Fortran 77 === |
=== Fortran 77 === |
||
< |
<syntaxhighlight lang="fortran"> FUNCTION HORNER(N,A,X) |
||
IMPLICIT NONE |
IMPLICIT NONE |
||
INTEGER I,N |
INTEGER I,N |
||
Line 787: | Line 787: | ||
END DO |
END DO |
||
HORNER=Y |
HORNER=Y |
||
END</ |
END</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="fortran"> SUBROUTINE HORNER2(N,A,X,Y,Z) |
||
C COMPUTE POLYNOMIAL VALUE AND DERIVATIVE |
C COMPUTE POLYNOMIAL VALUE AND DERIVATIVE |
||
C SEE "ROUNDOFF IN POLYNOMIAL EVALUATION", W. KAHAN, 1986 |
C SEE "ROUNDOFF IN POLYNOMIAL EVALUATION", W. KAHAN, 1986 |
||
Line 805: | Line 805: | ||
10 Y = Y*X + A(I) |
10 Y = Y*X + A(I) |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
Function AlgoritmoHorner(coeffs() As Integer, x As Integer) As Integer |
Function AlgoritmoHorner(coeffs() As Integer, x As Integer) As Integer |
||
Dim As Integer i, acumulador = 0 |
Dim As Integer i, acumulador = 0 |
||
Line 822: | Line 822: | ||
Print AlgoritmoHorner(coeficientes(), x) |
Print AlgoritmoHorner(coeficientes(), x) |
||
End |
End |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 830: | Line 830: | ||
=={{header|FunL}}== |
=={{header|FunL}}== |
||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
< |
<syntaxhighlight lang="funl">import lists.foldr |
||
def horner( poly, x ) = foldr( \a, b -> a + b*x, 0, poly ) |
def horner( poly, x ) = foldr( \a, b -> a + b*x, 0, poly ) |
||
println( horner([-19, 7, -4, 6], 3) )</ |
println( horner([-19, 7, -4, 6], 3) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 843: | Line 843: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
< |
<syntaxhighlight lang="futurebasic">include "NSLog.incl" |
||
local fn horner( coeffs as CFArrayRef, x as NSInteger ) as double |
local fn horner( coeffs as CFArrayRef, x as NSInteger ) as double |
||
Line 876: | Line 876: | ||
NSLog( @"%7.1f", fn horner( coeffs, 2 ) ) |
NSLog( @"%7.1f", fn horner( coeffs, 2 ) ) |
||
HandleEvents</ |
HandleEvents</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 889: | Line 889: | ||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># The idiomatic way to compute with polynomials |
||
x := Indeterminate(Rationals, "x"); |
x := Indeterminate(Rationals, "x"); |
||
Line 920: | Line 920: | ||
Horner(u, 3); |
Horner(u, 3); |
||
# 128</ |
# 128</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 936: | Line 936: | ||
func main() { |
func main() { |
||
fmt.Println(horner(3, []int64{-19, 7, -4, 6})) |
fmt.Println(horner(3, []int64{-19, 7, -4, 6})) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 944: | Line 944: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Solution: |
Solution: |
||
< |
<syntaxhighlight lang="groovy">def hornersRule = { coeff, x -> coeff.reverse().inject(0) { accum, c -> (accum * x) + c } }</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="groovy">def coefficients = [-19g, 7g, -4g, 6g] |
||
println (["p coefficients":coefficients]) |
println (["p coefficients":coefficients]) |
||
Line 969: | Line 969: | ||
def root = newtonRaphson(3g, testPoly, testDeriv) |
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]])</ |
println ([root:root.toString()[0..5], "p(root)":testPoly(root).toString()[0..5], "p'(root)":testDeriv(root).toString()[0..5]])</syntaxhighlight> |
||
Output: |
Output: |
||
Line 981: | Line 981: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">horner :: (Num a) => a -> [a] -> a |
||
horner x = foldr (\a b -> a + b*x) 0 |
horner x = foldr (\a b -> a + b*x) 0 |
||
main = print $ horner 3 [-19, 7, -4, 6]</ |
main = print $ horner 3 [-19, 7, -4, 6]</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">REAL :: x=3, coeffs(4) |
||
DATA coeffs/-19.0, 7.0, -4.0, 6.0/ |
DATA coeffs/-19.0, 7.0, -4.0, 6.0/ |
||
Line 998: | Line 998: | ||
Horner = x*Horner + c(i) |
Horner = x*Horner + c(i) |
||
ENDDO |
ENDDO |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
<syntaxhighlight lang="icon"> |
|||
<lang Icon> |
|||
procedure poly_eval (x, coeffs) |
procedure poly_eval (x, coeffs) |
||
accumulator := 0 |
accumulator := 0 |
||
Line 1,013: | Line 1,013: | ||
write (poly_eval (3, [-19, 7, -4, 6])) |
write (poly_eval (3, [-19, 7, -4, 6])) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution''':< |
'''Solution''':<syntaxhighlight lang="j"> |
||
horner =: (#."0 _ |.)~ NB. Tacit |
horner =: (#."0 _ |.)~ NB. Tacit |
||
horner =: [: +`*/ [: }: ,@,. NB. Alternate tacit (equivalent) |
horner =: [: +`*/ [: }: ,@,. NB. Alternate tacit (equivalent) |
||
horner =: 4 : ' (+ *&y)/x' NB. Alternate explicit (equivalent) |
horner =: 4 : ' (+ *&y)/x' NB. Alternate explicit (equivalent) |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Example''':< |
'''Example''':<syntaxhighlight lang="j"> _19 7 _4 6 horner 3 |
||
128</ |
128</syntaxhighlight> |
||
'''Note:'''<br> |
'''Note:'''<br> |
||
The primitive verb <code>p.</code> would normally be used to evaluate polynomials. |
The primitive verb <code>p.</code> would normally be used to evaluate polynomials. |
||
< |
<syntaxhighlight lang="j"> _19 7 _4 6 p. 3 |
||
128</ |
128</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
< |
<syntaxhighlight lang="java5">import java.util.ArrayList; |
||
import java.util.Collections; |
import java.util.Collections; |
||
import java.util.List; |
import java.util.List; |
||
Line 1,052: | Line 1,052: | ||
return accumulator; |
return accumulator; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>128.0</pre> |
<pre>128.0</pre> |
||
Line 1,060: | Line 1,060: | ||
{{trans|Haskell}} |
{{trans|Haskell}} |
||
< |
<syntaxhighlight lang="javascript">function horner(coeffs, x) { |
||
return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0); |
return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0); |
||
} |
} |
||
console.log(horner([-19,7,-4,6],3)); // ==> 128 |
console.log(horner([-19,7,-4,6],3)); // ==> 128 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Line 1,070: | Line 1,070: | ||
'''Imperative''': |
'''Imperative''': |
||
< |
<syntaxhighlight lang="julia">function horner(coefs, x) |
||
s = coefs[end] * one(x) |
s = coefs[end] * one(x) |
||
for k in length(coefs)-1:-1:1 |
for k in length(coefs)-1:-1:1 |
||
Line 1,078: | Line 1,078: | ||
end |
end |
||
@show horner([-19, 7, -4, 6], 3)</ |
@show horner([-19, 7, -4, 6], 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,084: | Line 1,084: | ||
'''Functional''': |
'''Functional''': |
||
< |
<syntaxhighlight lang="julia">horner2(coefs, x) = foldr((u, v) -> u + x * v, coefs, init=zero(promote_type(typeof(x),eltype(coefs)))) |
||
@show horner2([-19, 7, -4, 6], 3)</ |
@show horner2([-19, 7, -4, 6], 3)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,093: | Line 1,093: | ||
'''Note''': |
'''Note''': |
||
In Julia 1.4 or later one would normally use the built-in '''evalpoly''' function for this purpose: |
In Julia 1.4 or later one would normally use the built-in '''evalpoly''' function for this purpose: |
||
< |
<syntaxhighlight lang="julia"> |
||
@show evalpoly(3, [-19, 7, -4, 6]) </ |
@show evalpoly(3, [-19, 7, -4, 6]) </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,100: | Line 1,100: | ||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang K> |
|||
horner:{y _sv|x} |
horner:{y _sv|x} |
||
horner[-19 7 -4 6;3] |
horner[-19 7 -4 6;3] |
||
128 |
128 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.1.2 |
||
fun horner(coeffs: DoubleArray, x: Double): Double { |
fun horner(coeffs: DoubleArray, x: Double): Double { |
||
Line 1,118: | Line 1,118: | ||
val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0) |
val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0) |
||
println(horner(coeffs, 3.0)) |
println(horner(coeffs, 3.0)) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,126: | Line 1,126: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
{def horner |
{def horner |
||
{def horner.r |
{def horner.r |
||
Line 1,143: | Line 1,143: | ||
-> 2.220446049250313e-16 ~ 0 |
-> 2.220446049250313e-16 ~ 0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">src$ = "Hello" |
||
coefficients$ = "-19 7 -4 6" ' list coefficients of all x^0..x^n in order |
coefficients$ = "-19 7 -4 6" ' list coefficients of all x^0..x^n in order |
||
x = 3 |
x = 3 |
||
Line 1,165: | Line 1,165: | ||
horner = accumulator |
horner = accumulator |
||
end function |
end function |
||
</ |
</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to horner :x :coeffs |
||
if empty? :coeffs [output 0] |
if empty? :coeffs [output 0] |
||
output (first :coeffs) + (:x * horner :x bf :coeffs) |
output (first :coeffs) + (:x * horner :x bf :coeffs) |
||
end |
end |
||
show horner 3 [-19 7 -4 6] ; 128</ |
show horner 3 [-19 7 -4 6] ; 128</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function horners_rule( coeff, x ) |
||
local res = 0 |
local res = 0 |
||
for i = #coeff, 1, -1 do |
for i = #coeff, 1, -1 do |
||
Line 1,186: | Line 1,186: | ||
x = 3 |
x = 3 |
||
coefficients = { -19, 7, -4, 6 } |
coefficients = { -19, 7, -4, 6 } |
||
print( horners_rule( coefficients, x ) )</ |
print( horners_rule( coefficients, x ) )</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
applyhorner:=(L::list,x)->foldl((s,t)->s*x+t,op(ListTools:-Reverse(L))): |
applyhorner:=(L::list,x)->foldl((s,t)->s*x+t,op(ListTools:-Reverse(L))): |
||
Line 1,195: | Line 1,195: | ||
applyhorner([-19,7,-4,6],3); |
applyhorner([-19,7,-4,6],3); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,204: | Line 1,204: | ||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Horner[l_List, x_] := Fold[x #1 + #2 &, 0, l] |
||
Horner[{6, -4, 7, -19}, x] |
Horner[{6, -4, 7, -19}, x] |
||
-> -19 + x (7 + x (-4 + 6 x)) |
-> -19 + x (7 + x (-4 + 6 x)) |
||
-19 + x (7 + x (-4 + 6 x)) /. x -> 3 |
-19 + x (7 + x (-4 + 6 x)) /. x -> 3 |
||
-> 128</ |
-> 128</syntaxhighlight> |
||
=={{header|MATLAB}}== |
=={{header|MATLAB}}== |
||
< |
<syntaxhighlight lang="matlab">function accumulator = hornersRule(x,coefficients) |
||
accumulator = 0; |
accumulator = 0; |
||
Line 1,220: | Line 1,220: | ||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="matlab">>> hornersRule(3,[-19, 7, -4, 6]) |
||
ans = |
ans = |
||
128</ |
128</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="matlab">>> polyval(fliplr([-19, 7, -4, 6]),3) |
||
ans = |
ans = |
||
128</ |
128</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">/* Function horner already exists in Maxima, though it operates on expressions, not lists of coefficients */ |
||
horner(5*x^3+2*x+1); |
horner(5*x^3+2*x+1); |
||
x*(5*x^2+2)+1 |
x*(5*x^2+2)+1 |
||
Line 1,279: | Line 1,279: | ||
poleval([0, 0, 0, 0, 1], x); |
poleval([0, 0, 0, 0, 1], x); |
||
x^4</ |
x^4</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
< |
<syntaxhighlight lang="mercury"> |
||
:- module horner. |
:- module horner. |
||
:- interface. |
:- interface. |
||
Line 1,296: | Line 1,296: | ||
horner(X, Cs) = list.foldr((func(C, Acc) = Acc * X + C), Cs, 0). |
horner(X, Cs) = list.foldr((func(C, Acc) = Acc * X + C), Cs, 0). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|МК-61/52}}== |
=={{header|МК-61/52}}== |
||
<lang>ИП0 1 + П0 |
<syntaxhighlight lang="text">ИП0 1 + П0 |
||
ИПE ИПD * КИП0 + ПE |
ИПE ИПD * КИП0 + ПE |
||
ИП0 1 - x=0 04 |
ИП0 1 - x=0 04 |
||
ИПE С/П</ |
ИПE С/П</syntaxhighlight> |
||
''Input:'' Р1:РС - coefficients, Р0 - number of the coefficients, РD - ''x''. |
''Input:'' Р1:РС - coefficients, Р0 - number of the coefficients, РD - ''x''. |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula2">MODULE Horner; |
||
FROM RealStr IMPORT RealToStr; |
FROM RealStr IMPORT RealToStr; |
||
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
FROM Terminal IMPORT WriteString,WriteLn,ReadChar; |
||
Line 1,335: | Line 1,335: | ||
WriteLn; |
WriteLn; |
||
ReadChar |
ReadChar |
||
END Horner.</ |
END Horner.</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols nobinary |
options replace format comments java crossref savelog symbols nobinary |
||
Line 1,349: | Line 1,349: | ||
End |
End |
||
Say r |
Say r |
||
Say 6*x**3-4*x**2+7*x-19</ |
Say 6*x**3-4*x**2+7*x-19</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre>128 |
<pre>128 |
||
Line 1,355: | Line 1,355: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim"># You can also just use `reversed` proc from stdlib `algorithm` module |
||
iterator reversed[T](x: openArray[T]): T = |
iterator reversed[T](x: openArray[T]): T = |
||
for i in countdown(x.high, x.low): |
for i in countdown(x.high, x.low): |
||
Line 1,364: | Line 1,364: | ||
result = result * x + c |
result = result * x + c |
||
echo horner([-19, 7, -4, 6], 3)</ |
echo horner([-19, 7, -4, 6], 3)</syntaxhighlight> |
||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{works with|oo2c}} |
{{works with|oo2c}} |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE HornerRule; |
MODULE HornerRule; |
||
IMPORT |
IMPORT |
||
Line 1,397: | Line 1,397: | ||
Out.Int(Eval(coefs^,4,3),0);Out.Ln |
Out.Int(Eval(coefs^,4,3),0);Out.Ln |
||
END HornerRule. |
END HornerRule. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,404: | Line 1,404: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck"> |
||
class Horner { |
class Horner { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
Line 1,424: | Line 1,424: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
{{works with|Mac OS X|10.6+}} Using blocks |
{{works with|Mac OS X|10.6+}} Using blocks |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
typedef double (^mfunc)(double, double); |
typedef double (^mfunc)(double, double); |
||
Line 1,469: | Line 1,469: | ||
} |
} |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml"># let horner coeffs x = |
||
List.fold_left (fun acc coef -> acc * x + coef) 0 (List.rev coeffs) ;; |
List.fold_left (fun acc coef -> acc * x + coef) 0 (List.rev coeffs) ;; |
||
val horner : int list -> int -> int = <fun> |
val horner : int list -> int -> int = <fun> |
||
Line 1,479: | Line 1,479: | ||
# let coeffs = [-19; 7; -4; 6] in |
# let coeffs = [-19; 7; -4; 6] in |
||
horner coeffs 3 ;; |
horner coeffs 3 ;; |
||
- : int = 128</ |
- : int = 128</syntaxhighlight> |
||
It's also possible to do fold_right instead of reversing and doing fold_left; but fold_right is not tail-recursive. |
It's also possible to do fold_right instead of reversing and doing fold_left; but fold_right is not tail-recursive. |
||
=={{header|Octave}}== |
=={{header|Octave}}== |
||
< |
<syntaxhighlight lang="octave">function r = horner(a, x) |
||
r = 0.0; |
r = 0.0; |
||
for i = length(a):-1:1 |
for i = length(a):-1:1 |
||
Line 1,490: | Line 1,490: | ||
endfunction |
endfunction |
||
horner([-19, 7, -4, 6], 3)</ |
horner([-19, 7, -4, 6], 3)</syntaxhighlight> |
||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
< |
<syntaxhighlight lang="oorexx">/* Rexx --------------------------------------------------------------- |
||
* 04.03.2014 Walter Pachl |
* 04.03.2014 Walter Pachl |
||
*--------------------------------------------------------------------*/ |
*--------------------------------------------------------------------*/ |
||
Line 1,504: | Line 1,504: | ||
End |
End |
||
Say r |
Say r |
||
Say 6*x**3-4*x**2+7*x-19</ |
Say 6*x**3-4*x**2+7*x-19</syntaxhighlight> |
||
'''Output:''' |
'''Output:''' |
||
<pre>128 |
<pre>128 |
||
Line 1,510: | Line 1,510: | ||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {Horner Coeffs X} |
fun {Horner Coeffs X} |
||
{FoldL1 {Reverse Coeffs} |
{FoldL1 {Reverse Coeffs} |
||
Line 1,522: | Line 1,522: | ||
end |
end |
||
in |
in |
||
{Show {Horner [~19 7 ~4 6] 3}}</ |
{Show {Horner [~19 7 ~4 6] 3}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Also note that Pari has a polynomial type. Evaluating these is as simple as <code>subst(P,variable(P),x)</code>. |
Also note that Pari has a polynomial type. Evaluating these is as simple as <code>subst(P,variable(P),x)</code>. |
||
< |
<syntaxhighlight lang="parigp">horner(v,x)={ |
||
my(s=0); |
my(s=0); |
||
forstep(i=#v,1,-1,s=s*x+v[i]); |
forstep(i=#v,1,-1,s=s*x+v[i]); |
||
s |
s |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program HornerDemo(output); |
||
function horner(a: array of double; x: double): double; |
function horner(a: array of double; x: double): double; |
||
Line 1,550: | Line 1,550: | ||
write ('Horner calculated polynomial of 6*x^3 - 4*x^2 + 7*x - 19 for x = 3: '); |
write ('Horner calculated polynomial of 6*x^3 - 4*x^2 + 7*x - 19 for x = 3: '); |
||
writeln (horner (poly, 3.0):8:4); |
writeln (horner (poly, 3.0):8:4); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Horner calculated polynomial of 6*x^3 - 4*x^2 + 7*x - 19 for x = 3: 128.0000 |
<pre>Horner calculated polynomial of 6*x^3 - 4*x^2 + 7*x - 19 for x = 3: 128.0000 |
||
Line 1,556: | Line 1,556: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use 5.10.0; |
||
use strict; |
use strict; |
||
use warnings; |
use warnings; |
||
Line 1,569: | Line 1,569: | ||
my @coeff = (-19.0, 7, -4, 6); |
my @coeff = (-19.0, 7, -4, 6); |
||
my $x = 3; |
my $x = 3; |
||
say horner @coeff, $x;</ |
say horner @coeff, $x;</syntaxhighlight> |
||
===<!-- Perl -->Functional version=== |
===<!-- Perl -->Functional version=== |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use List::Util qw(reduce); |
use List::Util qw(reduce); |
||
Line 1,582: | Line 1,582: | ||
my @coeff = (-19.0, 7, -4, 6); |
my @coeff = (-19.0, 7, -4, 6); |
||
my $x = 3; |
my $x = 3; |
||
print horner(\@coeff, $x), "\n";</ |
print horner(\@coeff, $x), "\n";</syntaxhighlight> |
||
===<!-- Perl -->Recursive version=== |
===<!-- Perl -->Recursive version=== |
||
< |
<syntaxhighlight lang="perl">sub horner { |
||
my ($coeff, $x) = @_; |
my ($coeff, $x) = @_; |
||
@$coeff and |
@$coeff and |
||
Line 1,591: | Line 1,591: | ||
} |
} |
||
print horner( [ -19, 7, -4, 6 ], 3 );</ |
print horner( [ -19, 7, -4, 6 ], 3 );</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<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> |
<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,605: | Line 1,605: | ||
<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> |
<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> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,612: | Line 1,612: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
function horner($coeff, $x) { |
function horner($coeff, $x) { |
||
$result = 0; |
$result = 0; |
||
Line 1,623: | Line 1,623: | ||
$x = 3; |
$x = 3; |
||
echo horner($coeff, $x), "\n"; |
echo horner($coeff, $x), "\n"; |
||
?></ |
?></syntaxhighlight> |
||
===Functional version=== |
===Functional version=== |
||
{{works with|PHP|5.3+}} |
{{works with|PHP|5.3+}} |
||
< |
<syntaxhighlight lang="php"><?php |
||
function horner($coeff, $x) { |
function horner($coeff, $x) { |
||
return array_reduce(array_reverse($coeff), function ($a, $b) use ($x) { return $a * $x + $b; }, 0); |
return array_reduce(array_reverse($coeff), function ($a, $b) use ($x) { return $a * $x + $b; }, 0); |
||
Line 1,635: | Line 1,635: | ||
$x = 3; |
$x = 3; |
||
echo horner($coeff, $x), "\n"; |
echo horner($coeff, $x), "\n"; |
||
?></ |
?></syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
===Recursion=== |
===Recursion=== |
||
< |
<syntaxhighlight lang="picat">horner([],_X,0). |
||
horner([H|T],X,V) :- |
horner([H|T],X,V) :- |
||
horner(T,X,V1), |
horner(T,X,V1), |
||
V = V1 * X + H.</ |
V = V1 * X + H.</syntaxhighlight> |
||
===Iterative=== |
===Iterative=== |
||
< |
<syntaxhighlight lang="picat">horner2(Coeff, X, V) => |
||
Acc = 0, |
Acc = 0, |
||
foreach(I in Coeff.length..-1..1) |
foreach(I in Coeff.length..-1..1) |
||
Acc := Acc*X + Coeff[I] |
Acc := Acc*X + Coeff[I] |
||
end, |
end, |
||
V = Acc.</ |
V = Acc.</syntaxhighlight> |
||
===Functional approach=== |
===Functional approach=== |
||
< |
<syntaxhighlight lang="picat">h3(X,A,B) = A+B*X. |
||
horner3(Coeff, X) = fold($h3(X),0,Coeff.reverse()).</ |
horner3(Coeff, X) = fold($h3(X),0,Coeff.reverse()).</syntaxhighlight> |
||
===Test=== |
===Test=== |
||
< |
<syntaxhighlight lang="picat">go => |
||
horner([-19, 7, -4, 6], 3, V), |
horner([-19, 7, -4, 6], 3, V), |
||
println(V), |
println(V), |
||
Line 1,666: | Line 1,666: | ||
V3 = horner3([-19, 7, -4, 6], 3), |
V3 = horner3([-19, 7, -4, 6], 3), |
||
println(V3), |
println(V3), |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,674: | Line 1,674: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de horner (Coeffs X) |
||
(let Res 0 |
(let Res 0 |
||
(for C (reverse Coeffs) |
(for C (reverse Coeffs) |
||
(setq Res (+ C (* X Res))) ) ) )</ |
(setq Res (+ C (* X Res))) ) ) )</syntaxhighlight> |
||
< |
<syntaxhighlight lang="picolisp">: (horner (-19.0 7.0 -4.0 6.0) 3.0) |
||
-> 128</ |
-> 128</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
declare (i, n) fixed binary, (x, value) float; /* 11 May 2010 */ |
declare (i, n) fixed binary, (x, value) float; /* 11 May 2010 */ |
||
get (x); |
get (x); |
||
Line 1,695: | Line 1,695: | ||
put (value); |
put (value); |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Potion}}== |
=={{header|Potion}}== |
||
< |
<syntaxhighlight lang="potion">horner = (x, coef) : |
||
result = 0 |
result = 0 |
||
coef reverse each (a) : |
coef reverse each (a) : |
||
Line 1,706: | Line 1,706: | ||
. |
. |
||
horner(3, (-19, 7, -4, 6)) print</ |
horner(3, (-19, 7, -4, 6)) print</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
{{works with|PowerShell|4.0}} |
{{works with|PowerShell|4.0}} |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
function horner($coefficients, $x) { |
function horner($coefficients, $x) { |
||
$accumulator = 0 |
$accumulator = 0 |
||
Line 1,721: | Line 1,721: | ||
$x = 3 |
$x = 3 |
||
horner $coefficients $x |
horner $coefficients $x |
||
</syntaxhighlight> |
|||
</lang> |
|||
<b>Output:</b> |
<b>Output:</b> |
||
<pre> |
<pre> |
||
Line 1,729: | Line 1,729: | ||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Tested with SWI-Prolog. Works with other dialects. |
Tested with SWI-Prolog. Works with other dialects. |
||
< |
<syntaxhighlight lang="prolog">horner([], _X, 0). |
||
horner([H|T], X, V) :- |
horner([H|T], X, V) :- |
||
horner(T, X, V1), |
horner(T, X, V1), |
||
V is V1 * X + H. |
V is V1 * X + H. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output : |
Output : |
||
< |
<syntaxhighlight lang="prolog"> ?- horner([-19, 7, -4, 6], 3, V). |
||
V = 128.</ |
V = 128.</syntaxhighlight> |
||
===Functional approach=== |
===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 |
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 |
||
< |
<syntaxhighlight lang="prolog">:- use_module(library(lambda)). |
||
Line 1,753: | Line 1,753: | ||
f_horner(L, V, R) :- |
f_horner(L, V, R) :- |
||
foldr(\X^Y^Z^(Z is X * V + Y), 0, L, R). |
foldr(\X^Y^Z^(Z is X * V + Y), 0, L, R). |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Functional syntax (Ciao)=== |
===Functional syntax (Ciao)=== |
||
Works with Ciao (https://github.com/ciao-lang/ciao) and the fsyntax package: |
Works with Ciao (https://github.com/ciao-lang/ciao) and the fsyntax package: |
||
<syntaxhighlight lang="prolog"> |
|||
<lang Prolog> |
|||
:- module(_, [horner/3], [fsyntax, hiord]). |
:- module(_, [horner/3], [fsyntax, hiord]). |
||
:- use_module(library(hiordlib)). |
:- use_module(library(hiordlib)). |
||
horner(L, X) := ~foldr((''(H,V0,V) :- V is V0*X + H), L, 0). |
horner(L, X) := ~foldr((''(H,V0,V) :- V is V0*X + H), L, 0). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure Horner(List Coefficients(), b) |
||
Define result |
Define result |
||
ForEach Coefficients() |
ForEach Coefficients() |
||
Line 1,770: | Line 1,770: | ||
Next |
Next |
||
ProcedureReturn result |
ProcedureReturn result |
||
EndProcedure</ |
EndProcedure</syntaxhighlight> |
||
'''Implemented as |
'''Implemented as |
||
< |
<syntaxhighlight lang="purebasic">NewList a() |
||
AddElement(a()): a()= 6 |
AddElement(a()): a()= 6 |
||
AddElement(a()): a()= -4 |
AddElement(a()): a()= -4 |
||
AddElement(a()): a()= 7 |
AddElement(a()): a()= 7 |
||
AddElement(a()): a()=-19 |
AddElement(a()): a()=-19 |
||
Debug Horner(a(),3)</ |
Debug Horner(a(),3)</syntaxhighlight> |
||
'''Outputs |
'''Outputs |
||
128 |
128 |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">>>> def horner(coeffs, x): |
||
acc = 0 |
acc = 0 |
||
for c in reversed(coeffs): |
for c in reversed(coeffs): |
||
Line 1,790: | Line 1,790: | ||
>>> horner( (-19, 7, -4, 6), 3) |
>>> horner( (-19, 7, -4, 6), 3) |
||
128</ |
128</syntaxhighlight> |
||
===Functional version=== |
===Functional version=== |
||
< |
<syntaxhighlight lang="python">>>> try: from functools import reduce |
||
except: pass |
except: pass |
||
Line 1,800: | Line 1,800: | ||
>>> horner( (-19, 7, -4, 6), 3) |
>>> horner( (-19, 7, -4, 6), 3) |
||
128</ |
128</syntaxhighlight> |
||
==={{libheader|NumPy}}=== |
==={{libheader|NumPy}}=== |
||
< |
<syntaxhighlight lang="python">>>> import numpy |
||
>>> numpy.polynomial.polynomial.polyval(3, (-19, 7, -4, 6)) |
>>> numpy.polynomial.polynomial.polyval(3, (-19, 7, -4, 6)) |
||
128.0</ |
128.0</syntaxhighlight> |
||
=={{header|R}}== |
=={{header|R}}== |
||
Procedural style: |
Procedural style: |
||
< |
<syntaxhighlight lang="r">horner <- function(a, x) { |
||
y <- 0 |
y <- 0 |
||
for(c in rev(a)) { |
for(c in rev(a)) { |
||
Line 1,817: | Line 1,817: | ||
} |
} |
||
cat(horner(c(-19, 7, -4, 6), 3), "\n")</ |
cat(horner(c(-19, 7, -4, 6), 3), "\n")</syntaxhighlight> |
||
Functional style: |
Functional style: |
||
< |
<syntaxhighlight lang="r">horner <- function(x, v) { |
||
Reduce(v, right=T, f=function(a, b) { |
Reduce(v, right=T, f=function(a, b) { |
||
b * x + a |
b * x + a |
||
}) |
}) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,834: | Line 1,834: | ||
Translated from Haskell |
Translated from Haskell |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
(define (horner x l) |
(define (horner x l) |
||
Line 1,841: | Line 1,841: | ||
(horner 3 '(-19 7 -4 6)) |
(horner 3 '(-19 7 -4 6)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>sub horner ( @coeffs, $x ) { |
||
@coeffs.reverse.reduce: { $^a * $x + $^b }; |
@coeffs.reverse.reduce: { $^a * $x + $^b }; |
||
} |
} |
||
say horner( [ -19, 7, -4, 6 ], 3 );</ |
say horner( [ -19, 7, -4, 6 ], 3 );</syntaxhighlight> |
||
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: |
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: |
||
<lang |
<syntaxhighlight lang="raku" line>multi horner(Numeric $c, $) { $c } |
||
multi horner(Pair $c, $x) { |
multi horner(Pair $c, $x) { |
||
$c.key + $x * horner( $c.value, $x ) |
$c.key + $x * horner( $c.value, $x ) |
||
} |
} |
||
say horner( [=>](-19, 7, -4, 6 ), 3 );</ |
say horner( [=>](-19, 7, -4, 6 ), 3 );</syntaxhighlight> |
||
We can also use the composition operator: |
We can also use the composition operator: |
||
<lang |
<syntaxhighlight lang="raku" line>sub horner ( @coeffs, $x ) { |
||
([o] map { $_ + $x * * }, @coeffs)(0); |
([o] map { $_ + $x * * }, @coeffs)(0); |
||
} |
} |
||
say horner( [ -19, 7, -4, 6 ], 3 );</ |
say horner( [ -19, 7, -4, 6 ], 3 );</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,871: | Line 1,871: | ||
One advantage of using the composition operator is that it allows for the use of an infinite list of coefficients. |
One advantage of using the composition operator is that it allows for the use of an infinite list of coefficients. |
||
<lang |
<syntaxhighlight lang="raku" line>sub horner ( @coeffs, $x ) { |
||
map { .(0) }, [\o] map { $_ + $x * * }, @coeffs; |
map { .(0) }, [\o] map { $_ + $x * * }, @coeffs; |
||
} |
} |
||
say horner( [ 1 X/ (1, |[\*] 1 .. *) ], i*pi )[20]; |
say horner( [ 1 X/ (1, |[\*] 1 .. *) ], i*pi )[20]; |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>-0.999999999924349-5.28918515954219e-10i</pre> |
<pre>-0.999999999924349-5.28918515954219e-10i</pre> |
||
=={{header|Rascal}}== |
=={{header|Rascal}}== |
||
< |
<syntaxhighlight lang="rascal">import List; |
||
public int horners_rule(list[int] coefficients, int x){ |
public int horners_rule(list[int] coefficients, int x){ |
||
Line 1,888: | Line 1,888: | ||
acc = acc * x + i;} |
acc = acc * x + i;} |
||
return acc; |
return acc; |
||
}</ |
}</syntaxhighlight> |
||
A neater and shorter solution using a reducer: |
A neater and shorter solution using a reducer: |
||
< |
<syntaxhighlight lang="rascal">public int horners_rule2(list[int] coefficients, int x) = (0 | it * x + c | c <- reverse(coefficients));</syntaxhighlight> |
||
Output: |
Output: |
||
< |
<syntaxhighlight lang="rascal">rascal>horners_rule([-19, 7, -4, 6], 3) |
||
int: 128 |
int: 128 |
||
rascal>horners_rule2([-19, 7, -4, 6], 3) |
rascal>horners_rule2([-19, 7, -4, 6], 3) |
||
int: 128</ |
int: 128</syntaxhighlight> |
||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">REBOL [] |
||
horner: func [coeffs x] [ |
horner: func [coeffs x] [ |
||
Line 1,910: | Line 1,910: | ||
] |
] |
||
print horner [-19 7 -4 6] 3</ |
print horner [-19 7 -4 6] 3</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 1=== |
===version 1=== |
||
< |
<syntaxhighlight lang="rexx">/*REXX program demonstrates using Horner's rule for polynomial evaluation. */ |
||
numeric digits 30 /*use extra numeric precision. */ |
numeric digits 30 /*use extra numeric precision. */ |
||
parse arg x poly /*get value of X and the coefficients. */ |
parse arg x poly /*get value of X and the coefficients. */ |
||
Line 1,932: | Line 1,932: | ||
end /*j*/ |
end /*j*/ |
||
say /*display a blank line for readability.*/ |
say /*display a blank line for readability.*/ |
||
say ' answer = ' a /*stick a fork in it, we're all done. */</ |
say ' answer = ' a /*stick a fork in it, we're all done. */</syntaxhighlight> |
||
'''output''' when the following is used for input: <tt> 3 -19 7 -4 6 </tt> |
'''output''' when the following is used for input: <tt> 3 -19 7 -4 6 </tt> |
||
<pre> |
<pre> |
||
Line 1,943: | Line 1,943: | ||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang="rexx">/* REXX --------------------------------------------------------------- |
||
* 27.07.2012 Walter Pachl |
* 27.07.2012 Walter Pachl |
||
* coefficients reversed to descending order of power |
* coefficients reversed to descending order of power |
||
Line 1,987: | Line 1,987: | ||
Say ' equation = ' equ |
Say ' equation = ' equ |
||
Say ' ' |
Say ' ' |
||
Say ' result = ' a</ |
Say ' result = ' a</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> x = 3 |
<pre> x = 3 |
||
Line 1,996: | Line 1,996: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
coefficients = [-19, 7, -4, 6] |
coefficients = [-19, 7, -4, 6] |
||
see "x = 3" + nl + |
see "x = 3" + nl + |
||
Line 2,009: | Line 2,009: | ||
next |
next |
||
return w |
return w |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,025: | Line 2,025: | ||
This said, solution to the problem is |
This said, solution to the problem is |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> a = [6, -4, 7, -19] |
>> a = [6, -4, 7, -19] |
||
6 -4 7 -19 |
6 -4 7 -19 |
||
Line 2,033: | Line 2,033: | ||
128 |
128 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">def horner(coeffs, x) |
||
coeffs.reverse.inject(0) {|acc, coeff| acc * x + coeff} |
coeffs.reverse.inject(0) {|acc, coeff| acc * x + coeff} |
||
end |
end |
||
p horner([-19, 7, -4, 6], 3) # ==> 128</ |
p horner([-19, 7, -4, 6], 3) # ==> 128</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">coef$ = "-19 7 -4 6" ' list coefficients of all x^0..x^n in order |
||
x = 3 |
x = 3 |
||
print horner(coef$,x) '128 |
print horner(coef$,x) '128 |
||
Line 2,058: | Line 2,058: | ||
next |
next |
||
horner = accum |
horner = accum |
||
end function</ |
end function</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn horner(v: &[f64], x: f64) -> f64 { |
||
v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff) |
v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff) |
||
} |
} |
||
Line 2,068: | Line 2,068: | ||
let v = [-19., 7., -4., 6.]; |
let v = [-19., 7., -4., 6.]; |
||
println!("result: {}", horner(&v, 3.0)); |
println!("result: {}", horner(&v, 3.0)); |
||
}</ |
}</syntaxhighlight> |
||
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. |
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. |
||
< |
<syntaxhighlight lang="rust">extern crate num; // 0.2.0 |
||
use num::Zero; |
use num::Zero; |
||
use std::ops::{Add, Mul}; |
use std::ops::{Add, Mul}; |
||
Line 2,090: | Line 2,090: | ||
let output: f64 = horner(&v, 3.0); |
let output: f64 = horner(&v, 3.0); |
||
println!("result: {}", output); |
println!("result: {}", output); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang="sather">class MAIN is |
||
action(s, e, x:FLT):FLT is |
action(s, e, x:FLT):FLT is |
||
Line 2,107: | Line 2,107: | ||
#OUT + horner(|-19.0, 7.0, -4.0, 6.0|, 3.0) + "\n"; |
#OUT + horner(|-19.0, 7.0, -4.0, 6.0|, 3.0) + "\n"; |
||
end; |
end; |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">def horner(coeffs:List[Double], x:Double)= |
||
coeffs.reverse.foldLeft(0.0){(a,c)=> a*x+c} |
coeffs.reverse.foldLeft(0.0){(a,c)=> a*x+c} |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="scala">val coeffs=List(-19.0, 7.0, -4.0, 6.0) |
||
println(horner(coeffs, 3)) |
println(horner(coeffs, 3)) |
||
-> 128.0 |
-> 128.0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
{{Works with|Scheme|R<math>^5</math>RS}} |
{{Works with|Scheme|R<math>^5</math>RS}} |
||
< |
<syntaxhighlight lang="scheme">(define (horner lst x) |
||
(define (*horner lst x acc) |
(define (*horner lst x acc) |
||
(if (null? lst) |
(if (null? lst) |
||
Line 2,128: | Line 2,128: | ||
(display (horner (list -19 7 -4 6) 3)) |
(display (horner (list -19 7 -4 6) 3)) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
Output: |
Output: |
||
<lang>128</ |
<syntaxhighlight lang="text">128</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "float.s7i"; |
include "float.s7i"; |
||
Line 2,154: | Line 2,154: | ||
begin |
begin |
||
writeln(horner(coeffs, 3.0) digits 1); |
writeln(horner(coeffs, 3.0) digits 1); |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,163: | Line 2,163: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
Functional: |
Functional: |
||
< |
<syntaxhighlight lang="ruby">func horner(coeff, x) { |
||
coeff.reverse.reduce { |a,b| a*x + b }; |
coeff.reverse.reduce { |a,b| a*x + b }; |
||
} |
} |
||
say horner([-19, 7, -4, 6], 3); # => 128</ |
say horner([-19, 7, -4, 6], 3); # => 128</syntaxhighlight> |
||
Recursive: |
Recursive: |
||
< |
<syntaxhighlight lang="ruby">func horner(coeff, x) { |
||
coeff.len > 0 |
coeff.len > 0 |
||
&& (coeff[0] + x*horner(coeff.ft(1), x)); |
&& (coeff[0] + x*horner(coeff.ft(1), x)); |
||
} |
} |
||
say horner([-19, 7, -4, 6], 3); # => 128</ |
say horner([-19, 7, -4, 6], 3); # => 128</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
{{works with|GNU Smalltalk}} |
{{works with|GNU Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">OrderedCollection extend [ |
||
horner: aValue [ |
horner: aValue [ |
||
^ self reverse inject: 0 into: [:acc :c | acc * aValue + c]. |
^ self reverse inject: 0 into: [:acc :c | acc * aValue + c]. |
||
Line 2,185: | Line 2,185: | ||
]. |
]. |
||
(#(-19 7 -4 6) asOrderedCollection horner: 3) displayNl.</ |
(#(-19 7 -4 6) asOrderedCollection horner: 3) displayNl.</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">(* Assuming real type for coefficients and x *) |
||
fun horner coeffList x = foldr (fn (a, b) => a + b * x) (0.0) coeffList</ |
fun horner coeffList x = foldr (fn (a, b) => a + b * x) (0.0) coeffList</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">func horner(coefs: [Double], x: Double) -> Double { |
||
return reduce(lazy(coefs).reverse(), 0) { $0 * x + $1 } |
return reduce(lazy(coefs).reverse(), 0) { $0 * x + $1 } |
||
} |
} |
||
println(horner([-19, 7, -4, 6], 3))</ |
println(horner([-19, 7, -4, 6], 3))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>128.0</pre> |
<pre>128.0</pre> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
proc horner {coeffs x} { |
proc horner {coeffs x} { |
||
set y 0 |
set y 0 |
||
Line 2,208: | Line 2,208: | ||
} |
} |
||
return $y |
return $y |
||
}</ |
}</syntaxhighlight> |
||
Demonstrating: |
Demonstrating: |
||
< |
<syntaxhighlight lang="tcl">puts [horner {-19 7 -4 6} 3]</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>128</pre> |
<pre>128</pre> |
||
Line 2,218: | Line 2,218: | ||
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. |
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"> |
|||
<lang VBA> |
|||
Public Function Horner(x, ParamArray coeff()) |
Public Function Horner(x, ParamArray coeff()) |
||
Dim result As Double |
Dim result As Double |
||
Line 2,231: | Line 2,231: | ||
Horner = result |
Horner = result |
||
End Function |
End Function |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 2,240: | Line 2,240: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Function horners_rule(coefficients,x) |
Function horners_rule(coefficients,x) |
||
accumulator = 0 |
accumulator = 0 |
||
Line 2,250: | Line 2,250: | ||
WScript.StdOut.WriteLine horners_rule(Array(-19,7,-4,6),3) |
WScript.StdOut.WriteLine horners_rule(Array(-19,7,-4,6),3) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 2,257: | Line 2,257: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
{{trans|C#}} |
{{trans|C#}} |
||
< |
<syntaxhighlight lang="vbnet">Module Module1 |
||
Function Horner(coefficients As Double(), variable As Double) As Double |
Function Horner(coefficients As Double(), variable As Double) As Double |
||
Line 2,267: | Line 2,267: | ||
End Sub |
End Sub |
||
End Module</ |
End Module</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>128</pre> |
<pre>128</pre> |
||
Line 2,273: | Line 2,273: | ||
=={{header|Visual FoxPro}}== |
=={{header|Visual FoxPro}}== |
||
===Coefficients in ascending order.=== |
===Coefficients in ascending order.=== |
||
< |
<syntaxhighlight lang="vfp"> |
||
LOCAL x As Double |
LOCAL x As Double |
||
LOCAL ARRAY aCoeffs[1] |
LOCAL ARRAY aCoeffs[1] |
||
Line 2,293: | Line 2,293: | ||
RETURN s |
RETURN s |
||
ENDFUNC |
ENDFUNC |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Coefficients in descending order.=== |
===Coefficients in descending order.=== |
||
< |
<syntaxhighlight lang="vfp"> |
||
LOCAL x As Double |
LOCAL x As Double |
||
LOCAL ARRAY aCoeffs[1] |
LOCAL ARRAY aCoeffs[1] |
||
Line 2,315: | Line 2,315: | ||
RETURN s |
RETURN s |
||
ENDFUNC |
ENDFUNC |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang="vlang">fn horner(x i64, c []i64) i64 { |
||
mut acc := i64(0) |
mut acc := i64(0) |
||
for i := c.len - 1; i >= 0; i-- { |
for i := c.len - 1; i >= 0; i-- { |
||
Line 2,328: | Line 2,328: | ||
fn main() { |
fn main() { |
||
println(horner(3, [i64(-19), 7, -4, 6])) |
println(horner(3, [i64(-19), 7, -4, 6])) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,336: | Line 2,336: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="ecmascript">var horner = Fn.new { |x, c| |
||
var count = c.count |
var count = c.count |
||
if (count == 0) return 0 |
if (count == 0) return 0 |
||
Line 2,342: | Line 2,342: | ||
} |
} |
||
System.print(horner.call(3, [-19, 7, -4, 6]))</ |
System.print(horner.call(3, [-19, 7, -4, 6]))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,350: | Line 2,350: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">code IntOut=11; |
||
func Horner(X, N, C); \Return value of polynomial in X |
func Horner(X, N, C); \Return value of polynomial in X |
||
Line 2,361: | Line 2,361: | ||
]; |
]; |
||
IntOut(0, Horner(3, 4, [-19, 7, -4, 6]));</ |
IntOut(0, Horner(3, 4, [-19, 7, -4, 6]));</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,369: | Line 2,369: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">fcn horner(coeffs,x) |
||
{ coeffs.reverse().reduce('wrap(a,coeff){ a*x + coeff },0.0) }</ |
{ coeffs.reverse().reduce('wrap(a,coeff){ a*x + coeff },0.0) }</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |