How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Haskell programming language
How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Haskell programming language
Table of Contents
Problem Statement
A fast scheme for evaluating a polynomial such as: when is to arrange the computation as follows: And compute the result from the innermost brackets outwards as in this pseudocode: Task Description Cf. Formal power series
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Horner's rule for polynomial evaluation step by step in the Haskell programming language
The provided code defines a function horner
that evaluates a polynomial using Horner's method:
horner :: (Num a) => a -> [a] -> a
where:
a
: The type of the coefficients in the polynomial. It must be a numeric type that supports addition and multiplication (Num
).x
: The value to be evaluated at.[a]
: A list of coefficients representing the polynomial, with the coefficients in decreasing order of their exponents.
The horner
function uses the foldr
function to iteratively evaluate the polynomial using Horner's method. foldr
takes three arguments: a function to apply to each element of the list, an initial value, and the list itself. In this case, the function is:
(\a b -> a + b*x)
which takes two arguments:
a
: The accumulator, which initially starts with the value0
.b
: The current coefficient in the polynomial.
The function adds b*x
to the accumulator and returns the result. The foldr
function applies this function to every element of the list, accumulating the result in the accumulator variable.
The initial value for the accumulator is 0
, which represents the constant term in the polynomial.
The main
function simply calls the horner
function with the value 3
and the list [-19, 7, -4, 6]
, which represents the polynomial -19x^3 + 7x^2 - 4x + 6
. The result of the evaluation is then printed to the console.
In this case, the result will be -33
, which is the value of the polynomial -19x^3 + 7x^2 - 4x + 6
when evaluated at x=3
.
Source code in the haskell programming language
horner :: (Num a) => a -> [a] -> a
horner x = foldr (\a b -> a + b*x) 0
main = print $ horner 3 [-19, 7, -4, 6]
You may also check:How to resolve the algorithm Pythagorean triples step by step in the Ruby programming language
You may also check:How to resolve the algorithm Sailors, coconuts and a monkey problem step by step in the Julia programming language
You may also check:How to resolve the algorithm Combinations step by step in the C# programming language
You may also check:How to resolve the algorithm 15 puzzle game step by step in the Gambas programming language
You may also check:How to resolve the algorithm Respond to an unknown method call step by step in the Oforth programming language