@@ -866,6 +866,15 @@ which incur interpreter overhead.
866
866
window.append(x)
867
867
yield math.sumprod(kernel, window)
868
868
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
+
869
878
def polynomial_from_roots(roots):
870
879
"""Compute a polynomial's coefficients from its roots.
871
880
@@ -1245,6 +1254,37 @@ which incur interpreter overhead.
1245
1254
>>> list (convolve(data, [1 , - 2 , 1 ]))
1246
1255
[20, 0, -36, 24, -20, 20, -20, -4, 16]
1247
1256
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
+
1248
1288
>>> polynomial_from_roots([5 , - 4 , 3 ])
1249
1289
[1, -4, -17, 60]
1250
1290
>>> factored = lambda x : (x - 5 ) * (x + 4 ) * (x - 3 )
0 commit comments