[Python-checkins] Add itertool recipe for polynomial evaluation. (GH-102852)

rhettinger webhook-mailer at python.org
Mon Mar 20 18:14:36 EDT 2023


https://github.com/python/cpython/commit/094cf392f49d3c16fe798863717f6c8e0f3734bb
commit: 094cf392f49d3c16fe798863717f6c8e0f3734bb
branch: main
author: Raymond Hettinger <rhettinger at users.noreply.github.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2023-03-20T17:14:29-05:00
summary:

Add itertool recipe for polynomial evaluation. (GH-102852)

files:
M Doc/library/itertools.rst

diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index d85a17effb04..9364f72ca456 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)



More information about the Python-checkins mailing list