Polynomial Add 代码
时间: 2024-10-27 07:11:30 浏览: 7
dxs.rar_polynomial_多项式 java
多项式的加法是指将两个多项式的所有对应项相加得到一个新的多项式。这里有一个基本的Python代码示例,用于将两个多项式相加:
```python
class Polynomial:
def __init__(self, coefficients=None):
if coefficients is None:
self.coefficients = []
else:
self.coefficients = coefficients
def add(self, other):
# 确保两个多项式有相同的长度,如果长度不同,则增加零项到较短的多项式
min_len = min(len(self.coefficients), len(other.coefficients))
longer_poly = self if len(self) > len(other) else other
shorter_poly = other if len(self) < len(other) else self
# 初始化结果多项式
result = Polynomial()
for i in range(min_len):
result.coefficients.append(longer_poly.coefficients[i] + shorter_poly.coefficients[i])
# 添加剩余的非对齐项
for coefficient in longer_poly.coefficients[min_len:]:
result.coefficients.append(coefficient)
for coefficient in shorter_poly.coefficients[min_len:]:
result.coefficients.append(coefficient)
return result
def __str__(self):
terms = ' '.join(f'{coeff}x^{power}' for coeff, power in enumerate(self.coefficients, start=1) if coeff != 0)
return f'{terms}' if terms else '0'
# 使用示例
poly1 = Polynomial([2, 3, 1]) # 2x^2 + 3x + 1
poly2 = Polynomial([4, 1, 5]) # 4x^1 + 1 + 5x^0
added_poly = poly1.add(poly2)
print(added_poly) # 输出:6x^2 + 4x + 6
```
这个代码定义了一个`Polynomial`类,包含一个`add`方法用于相加两个多项式。`__str__`方法使得打印出来的多项式更易读。
阅读全文