Python 多项式 pow

Python polynomial pow

我有自己定义的多项式class,它是系数列表的形式。

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])

和list的len()取决于函数的索引。

我想定义一个自定义 __pow__ 函数,但我真的不知道如何实现它。

好的,这里有多个答案,具体取决于您定义“pow”函数的意思。

因此,首先,正如@matt 已经正确指出的那样,幂只是重复乘法。 Python 实际上有一个内置的 pow 函数,但也有使用 a**2 = a squared = a*aa**3 = a * a * aa**4=a * a * a * a 等的快速符号

现在,如果您只想要每个 x 参数的 pow,您的函数将如下所示

a*(x**2)+b*x+c 

a*(x**4)+b*(x**3)+c*(x**2)+d*x+e

最后,您可能希望列出您的系数,这样您就可以这样做

coefficients = [1,2,3,...] #(inputting real values here)
def poly(x):
     sum=0.0
     for i in range(len(coefficients)):
          sum+=coefficients[i]*(x**i)
     return sum

那可以 return 由系数列表 "coefficients" 和 return 定义的多项式给你任何点的值 "x".

希望对您有所帮助:)

edit:: 请阅读您的评论,稍后会将其附加到我的回答中。

我的第二次编辑打字有点太快了,只需使用其他答案提供的算法:)

edit2::

正如马特指出的那样::

 def __mult__(coeff1,coeff2):
     coeff_result = [0.0]*(len(coeff1)+len(coeff2)-1)
     for k in range(len(coeff1)):
         for n in range(len(coeff2)):
              coeff_result[k+n]+=coeff1[k]*coeff2[n]
     return coeff_result
 def __pow__(coeff1,n):
     res = coeff1[:]
     for i in range(n-1):
         res=__mult__(res,coeff1)
     return res

整数指数的技巧(非整数指数不会 return 有效的多项式)。

这是一个函数,可以在将两个多项式相乘时得到它们的系数。

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))

其中显示 [2.0, 3.0, 1.0, 0]

然后制作一个 pow 函数在循环中调用 multiply。

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))

按预期输出 [1.0, 4.0, 6.0, 4.0, 1.0]