Update itertool recipe: polynomial_from_roots() (GH-103973)
This commit is contained in:
parent
81387fe36e
commit
c3453fbb11
@ -789,6 +789,7 @@ which incur interpreter overhead.
|
|||||||
.. testcode::
|
.. testcode::
|
||||||
|
|
||||||
import collections
|
import collections
|
||||||
|
import functools
|
||||||
import math
|
import math
|
||||||
import operator
|
import operator
|
||||||
import random
|
import random
|
||||||
@ -1082,7 +1083,7 @@ The following recipes have a more mathematical flavor:
|
|||||||
# convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
|
# convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
|
||||||
kernel = tuple(kernel)[::-1]
|
kernel = tuple(kernel)[::-1]
|
||||||
n = len(kernel)
|
n = len(kernel)
|
||||||
padded_signal = chain(repeat(0, n-1), signal, [0] * (n-1))
|
padded_signal = chain(repeat(0, n-1), signal, repeat(0, n-1))
|
||||||
for window in sliding_window(padded_signal, n):
|
for window in sliding_window(padded_signal, n):
|
||||||
yield math.sumprod(kernel, window)
|
yield math.sumprod(kernel, window)
|
||||||
|
|
||||||
@ -1092,10 +1093,8 @@ The following recipes have a more mathematical flavor:
|
|||||||
(x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
|
(x - 5) (x + 4) (x - 3) expands to: x³ -4x² -17x + 60
|
||||||
"""
|
"""
|
||||||
# polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
|
# polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
|
||||||
expansion = [1]
|
factors = zip(repeat(1), map(operator.neg, roots))
|
||||||
for r in roots:
|
return list(functools.reduce(convolve, factors, [1]))
|
||||||
expansion = convolve(expansion, (1, -r))
|
|
||||||
return list(expansion)
|
|
||||||
|
|
||||||
def polynomial_eval(coefficients, x):
|
def polynomial_eval(coefficients, x):
|
||||||
"""Evaluate a polynomial at a specific value.
|
"""Evaluate a polynomial at a specific value.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user