define a polynomial of any degree in Python

0

Working with numerical calculus, my goal is to use a " least squares ". I'm defining a function in Python as follows:

def F(P,x):
    return P[0] + P[1]*x + P[2]*x**2 + P[3]*x**3

Then I will define these coefficients P [0], P [1], ...

This example is easy, because the polynomial is of degree 3, but I intend to make a polynomial of degree greater than 10. So I wanted to facilitate the definition of this polynomial. Let's say that before I define grade = 3, grade = 4 or any value and make it practical to define a polynomial of any degree in Python, that is, I choose the degree, say 3 and e define me returning as follows: >

def F(P,x):
    return P[0] + P[1]*x + P[2]*x^2 + P[3]*x^3

If I choose 4, return me as follows:

def F(P,x):
    return P[0] + P[1]*x + P[2]*x^2 + P[3]*x^3 + P[4]**x^4
    
asked by anonymous 01.11.2018 / 01:35

1 answer

0

Now it's simple - you really only want a function in Python that does the numeric calculation of the polynomial, defined by the coefficients in P.

Then you only have to do a for by traversing the coefficients, and using enmerate to have the exponent of X associated with each coefficient. The enumerate works like this: for each element of a sequence, it returns another two-element sequence in which the first is the index and the second is the element itself.

Then we calculate each portion of the polynomial and add them all up - doing "in extenso":

def F(P, x):
    result = 0
    for exponent, coeficient in enumerate(P):
        result += coeficient * x ** exponent
    return result

It works if P is a list or any other sequence, since for in Python always traverses a sequence.

There is a more advanced syntax that also allows the use of for as an "inline" expression, not as a command on a separate line. This template creates a "generator expression" that can be passed directly to the built-in function sum :

def F(P, x):
    return sum(c * x ** e for (e, c) in enumerate(P))

And last but not least, you can have a polynomial class - and over time add features to it - if the class receives a list of coefficients in its __init__ , it can have a __call__ which allows its polynomial to calculate its value for a given "x" - and a __repr__ that has a legal representation of the polynomial:

class Poli:
    def __init__(self, coeficients):
         self.coeficients = coeficients
    @property
    def degree(self):
         return len(coeficients) - 1
    def __call__(self, x):
         return sum(c * x ** e for (e, c) in enumerate(self.coeficients))
    def __repr__(self):
         return f"P({})".format(" + ".join(f"{c} * x ** {e}" for e, c in enumerate(self.coeficients))
    
01.11.2018 / 21:51