@@ -866,6 +866,17 @@ which incur interpreter overhead.
866
866
window.append(x)
867
867
yield math.sumprod(kernel, window)
868
868
869
+ def polynomial_from_roots(roots):
870
+ """Compute a polynomial's coefficients from its roots.
871
+
872
+ (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
873
+ """
874
+ # polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
875
+ expansion = [1]
876
+ for r in roots:
877
+ expansion = convolve(expansion, (1, -r))
878
+ return list(expansion)
879
+
869
880
def polynomial_eval(coefficients, x):
870
881
"""Evaluate a polynomial at a specific value.
871
882
@@ -876,20 +887,8 @@ which incur interpreter overhead.
876
887
n = len(coefficients)
877
888
if n == 0:
878
889
return x * 0 # coerce zero to the type of x
879
- powers = map(pow, repeat(x), range(n))
880
- return math.sumprod(reversed(coefficients), powers)
881
-
882
- def polynomial_from_roots(roots):
883
- """Compute a polynomial's coefficients from its roots.
884
-
885
- (x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
886
- """
887
- # polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
888
- roots = list(map(operator.neg, roots))
889
- return [
890
- sum(map(math.prod, combinations(roots, k)))
891
- for k in range(len(roots) + 1)
892
- ]
890
+ powers = map(pow, repeat(x), reversed(range(n)))
891
+ return math.sumprod(coefficients, powers)
893
892
894
893
def iter_index(iterable, value, start=0):
895
894
"Return indices where a value occurs in a sequence or iterable."
0 commit comments