Horner's rule for polynomial evaluation: Difference between revisions

Content added Content deleted
(Go solution)
Line 179: Line 179:


=={{header|D}}==
=={{header|D}}==
The poly() function of the standard library std.math module uses Horner's rule:
<lang d>import std.stdio ;
import std.traits ;
<lang d>import std.stdio, std.math;


void main() {
CommonType!(U,V) horner(U,V)(U[] p, V x) {
CommonType!(U,V) acc = 0 ;
writeln(poly(3.0, [-19, 7, -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)
accumulator = accumulator * x + c;
return accumulator;
}
}


void main() {
void main() {
auto poly = [-19, 7, -4 , 6] ;
auto poly = [-19, 7, -4, 6];
writefln("%s", poly.horner(3.0)) ;
writeln(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}}==
=={{header|Erlang}}==
<lang erlang>
<lang erlang>