diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2023-03-20 22:14:29 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-03-20 22:14:29 (GMT) |
commit | 094cf392f49d3c16fe798863717f6c8e0f3734bb (patch) | |
tree | b258caf7c67b4449b4aae90d607efd93e3a62c32 /Doc | |
parent | 5c75b7a91ca7ad4133d5a7e9c245268bcfdd993e (diff) | |
download | cpython-094cf392f49d3c16fe798863717f6c8e0f3734bb.zip cpython-094cf392f49d3c16fe798863717f6c8e0f3734bb.tar.gz cpython-094cf392f49d3c16fe798863717f6c8e0f3734bb.tar.bz2 |
Add itertool recipe for polynomial evaluation. (GH-102852)
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/itertools.rst | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index d85a17e..9364f72 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -866,6 +866,15 @@ which incur interpreter overhead. window.append(x) yield math.sumprod(kernel, window) + def polynomial_eval(coefficients, x): + "Evaluate a polynomial at a specific value." + # polynomial_eval([1, -4, -17, 60], x=2.5) --> 8.125 x³ -4x² -17x + 60 + n = len(coefficients) + if n == 0: + return x * 0 # coerce zero to the type of x + powers = list(accumulate(repeat(x, n - 1), operator.mul, initial=1)) + return math.sumprod(coefficients, reversed(powers)) + def polynomial_from_roots(roots): """Compute a polynomial's coefficients from its roots. @@ -1245,6 +1254,37 @@ which incur interpreter overhead. >>> list(convolve(data, [1, -2, 1])) [20, 0, -36, 24, -20, 20, -20, -4, 16] + >>> from fractions import Fraction + >>> from decimal import Decimal + >>> polynomial_eval([1, -4, -17, 60], x=2) + 18 + >>> x = 2; x**3 - 4*x**2 -17*x + 60 + 18 + >>> polynomial_eval([1, -4, -17, 60], x=2.5) + 8.125 + >>> x = 2.5; x**3 - 4*x**2 -17*x + 60 + 8.125 + >>> polynomial_eval([1, -4, -17, 60], x=Fraction(2, 3)) + Fraction(1274, 27) + >>> x = Fraction(2, 3); x**3 - 4*x**2 -17*x + 60 + Fraction(1274, 27) + >>> polynomial_eval([1, -4, -17, 60], x=Decimal('1.75')) + Decimal('23.359375') + >>> x = Decimal('1.75'); x**3 - 4*x**2 -17*x + 60 + Decimal('23.359375') + >>> polynomial_eval([], 2) + 0 + >>> polynomial_eval([], 2.5) + 0.0 + >>> polynomial_eval([], Fraction(2, 3)) + Fraction(0, 1) + >>> polynomial_eval([], Decimal('1.75')) + Decimal('0.00') + >>> polynomial_eval([11], 7) == 11 + True + >>> polynomial_eval([11, 2], 7) == 11 * 7 + 2 + True + >>> polynomial_from_roots([5, -4, 3]) [1, -4, -17, 60] >>> factored = lambda x: (x - 5) * (x + 4) * (x - 3) |