mathpython-3.6

Python polynomial pow


I have my own defined Polynomial class, which is in form of list of coefficients.
Something like

axˆ2 + bx + c is equals to [c, b, a]
(for ax + b == [b, a]
similarly, for axˆ3 + bxˆ2 + cx + d == [d, c, b, a])

and the len() of list depends of the index of function.

I want to define a custom __pow__ function but I really have no idea how to implement it.


Solution

  • Here is a function to get the coefficients of two polynomials when you multiply them together.

    def multiply(a, b):
        """
            polynomials where.
            [a1, a2, a3] -> a1 + a2*x + a3*x^2
            [b1, b2, b3] -> b1 + b2*x + b3*x^2
        """
        c = [0.0]*(len(a) + len(b)-1)
    
        for i in range(len(a)):
            ai = a[i]
            for j in range(len(b)):
                c[i + j] += ai * b[j]
    
        return c
    
    
    x = [1, 1]
    y = [2, 1, 0]
    print(multiply(x, y))
    

    Which shows [2.0, 3.0, 1.0, 0].

    Then make a pow function to call multiply in a loop.

    def pow(a, n):
        """
         a^n
        """
        c = [1]
        for i in range(n):
            c = multiply(c, a)
        return c
    
    x = [1, 1]
    print(pow(x, 4))
    

    Which outputs [1.0, 4.0, 6.0, 4.0, 1.0] as expected.