Horner's rule for polynomial evaluation: Difference between revisions

(Go solution)
Line 179:
 
=={{header|D}}==
The poly() function of the standard library std.math module uses Horner's rule:
<lang d>import std.stdio ;
<lang d>import std.traitsstdio, std.math;
 
void main() {
CommonType!(U,V) horner(U,V)(U[] p, V x) {
CommonType!writeln(Upoly(3.0,V) acc[-19, =7, 0-4, 6]));
}</lang>
foreach_reverse(c ; p)
Basic implementation:
acc = acc * x + c ;
<lang d>import std.stdio, std.traits;
return acc ;
 
CommonType!(U, V) horner(U, V)(U[] p, V x) {
typeof(return) accumulator = 0;
foreach_reverse (c ; p)
accaccumulator = accaccumulator * x + c ;
return acc accumulator;
}
 
void main() {
auto poly = [-19, 7, -4 , 6] ;
writeflnwriteln("%s", poly.horner(3.0)) ;
}</lang>
More functional:
<lang d>import std.stdio, std.algorithm, std.range;
 
auto horner(U, V)(U[] p, V x) {
return reduce!((a, b){ return a*x+b;})(cast(V)0, retro(p));
}
 
</lang>
void main() {
auto poly = [-19, 7, -4, 6];
writeln(poly.horner(3.0));
}</lang>
 
=={{header|Erlang}}==
<lang erlang>
Anonymous user