Anonymous user
Horner's rule for polynomial evaluation: Difference between revisions
Horner's rule for polynomial evaluation (view source)
Revision as of 22:48, 31 January 2011
, 13 years ago→{{header|D}}
(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.
void main() {
CommonType!(U,V) horner(U,V)(U[] p, V x) {▼
}</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;
}
void main() {
auto poly = [-19, 7, -4
}</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>
|