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: |
|||
⚫ | |||
import std. |
<lang d>import std.stdio, std.math; |
||
void main() { |
|||
⚫ | |||
writeln(poly(3.0, [-19, 7, -4, 6])); |
|||
⚫ | |||
⚫ | |||
Basic implementation: |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
typeof(return) accumulator = 0; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
} |
||
void main() { |
void main() { |
||
auto poly = [-19, 7, -4 |
auto poly = [-19, 7, -4, 6]; |
||
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)); |
|||
} |
} |
||
⚫ | |||
void main() { |
|||
auto poly = [-19, 7, -4, 6]; |
|||
writeln(poly.horner(3.0)); |
|||
}</lang> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
<lang erlang> |
<lang erlang> |