Skip to content

Commit 094cf39

Browse files
authored
Add itertool recipe for polynomial evaluation. (GH-102852)
1 parent 5c75b7a commit 094cf39

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Doc/library/itertools.rst

+40
Original file line numberDiff line numberDiff line change
@@ -866,6 +866,15 @@ which incur interpreter overhead.
866866
window.append(x)
867867
yield math.sumprod(kernel, window)
868868

869+
def polynomial_eval(coefficients, x):
870+
"Evaluate a polynomial at a specific value."
871+
# polynomial_eval([1, -4, -17, 60], x=2.5) --> 8.125 x³ -4x² -17x + 60
872+
n = len(coefficients)
873+
if n == 0:
874+
return x * 0 # coerce zero to the type of x
875+
powers = list(accumulate(repeat(x, n - 1), operator.mul, initial=1))
876+
return math.sumprod(coefficients, reversed(powers))
877+
869878
def polynomial_from_roots(roots):
870879
"""Compute a polynomial's coefficients from its roots.
871880

@@ -1245,6 +1254,37 @@ which incur interpreter overhead.
12451254
>>> list(convolve(data, [1, -2, 1]))
12461255
[20, 0, -36, 24, -20, 20, -20, -4, 16]
12471256

1257+
>>> from fractions import Fraction
1258+
>>> from decimal import Decimal
1259+
>>> polynomial_eval([1, -4, -17, 60], x=2)
1260+
18
1261+
>>> x = 2; x**3 - 4*x**2 -17*x + 60
1262+
18
1263+
>>> polynomial_eval([1, -4, -17, 60], x=2.5)
1264+
8.125
1265+
>>> x = 2.5; x**3 - 4*x**2 -17*x + 60
1266+
8.125
1267+
>>> polynomial_eval([1, -4, -17, 60], x=Fraction(2, 3))
1268+
Fraction(1274, 27)
1269+
>>> x = Fraction(2, 3); x**3 - 4*x**2 -17*x + 60
1270+
Fraction(1274, 27)
1271+
>>> polynomial_eval([1, -4, -17, 60], x=Decimal('1.75'))
1272+
Decimal('23.359375')
1273+
>>> x = Decimal('1.75'); x**3 - 4*x**2 -17*x + 60
1274+
Decimal('23.359375')
1275+
>>> polynomial_eval([], 2)
1276+
0
1277+
>>> polynomial_eval([], 2.5)
1278+
0.0
1279+
>>> polynomial_eval([], Fraction(2, 3))
1280+
Fraction(0, 1)
1281+
>>> polynomial_eval([], Decimal('1.75'))
1282+
Decimal('0.00')
1283+
>>> polynomial_eval([11], 7) == 11
1284+
True
1285+
>>> polynomial_eval([11, 2], 7) == 11 * 7 + 2
1286+
True
1287+
12481288
>>> polynomial_from_roots([5, -4, 3])
12491289
[1, -4, -17, 60]
12501290
>>> factored = lambda x: (x - 5) * (x + 4) * (x - 3)

0 commit comments

Comments
 (0)