'How to evaluate a polynomial at a specific x-value?
Use map
to evaluate a given polynomial at a specific x-value.
Input:
- p: A list of coefficients for increasing powers of x
- x: The value of x to evaluate
Output: Number representing the value of the evaluated polynomial
Example: poly_eval([1, 2, 3], 2) = 1(2)^0 + 2(2)^1 + 3(2)^2 = 17
Solution 1:[1]
def poly_eval(coeff_list, x):
total = 0
for i, coeff in enumerate(coeff_list):
total += coeff * x**i
return total
or if you really want to use map :
def poly_eval(coeff_list, x):
n = len(coeff_list)
return sum(map(lambda coeff, x, y: coeff*x**y, coeff_list, [x]*n, range(n)))
Solution 2:[2]
This is actually an interesting question. Since the answer is relatively simple and the pen and paper solution is known by everybody the real thing is kind of overlooked.
As mentioned, normally most people would approach like how it's done by pen and paper. However there is a better way which is more suitable for coding purposes, known as the Ruffini Horner method. This is a perfect case for reducing.
Write your polynomial in an array. So y = x^3-7x+7
would be var y = [1,0,-7,7]
.
Then a simple function;
var calcP = (y,x) => y.reduce((p,c) => p*x+c);
That's it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |