我有自己定义的多项式类,它是系数列表的形式.
就像是
ax2 + bx + c等于[c,b,a]
(对于ax + b == [b,a],
类似地,对于ax3 + bx2 + cx + d == [d,c,b,a])
列表的len()取决于函数的索引.
我想定义一个自定义__pow__函数,但我真的不知道如何实现它.
这是一个函数,用于在将两个多项式相乘时得到两个多项式的系数.
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))
Run Code Online (Sandbox Code Playgroud)
哪个节目[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))
Run Code Online (Sandbox Code Playgroud)
哪个输出[1.0, 4.0, 6.0, 4.0, 1.0]符合预期.
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |