设计一个简单一元多项式计算器
时间: 2023-12-29 12:04:25 浏览: 101
好的,我可以为您设计一个简单的一元多项式计算器。
首先,我们需要定义一个多项式的类,包含如下属性和方法:
- 属性:系数数组coeffs,表示多项式的系数;次数degree,表示多项式的最高次数。
- 方法:构造函数__init__,用于初始化多项式;重载运算符__add__、__sub__、__mul__、__truediv__和__str__,用于实现多项式的加减乘除和字符串输出。
以下是一个简单的实现:
```python
class Polynomial:
def __init__(self, coeffs):
self.coeffs = coeffs
self.degree = len(coeffs) - 1
def __add__(self, other):
if self.degree < other.degree:
return other + self
coeffs = [self.coeffs[i] + (other.coeffs[i] if i <= other.degree else 0)
for i in range(self.degree + 1)]
return Polynomial(coeffs)
def __sub__(self, other):
coeffs = [self.coeffs[i] - (other.coeffs[i] if i <= other.degree else 0)
for i in range(self.degree + 1)]
return Polynomial(coeffs)
def __mul__(self, other):
coeffs = [0] * (self.degree + other.degree + 1)
for i in range(self.degree + 1):
for j in range(other.degree + 1):
coeffs[i+j] += self.coeffs[i] * other.coeffs[j]
return Polynomial(coeffs)
def __truediv__(self, other):
if other.degree == 0:
return Polynomial([self.coeffs[i] / other.coeffs[0] for i in range(self.degree + 1)])
q = Polynomial([0] * (self.degree - other.degree + 1))
r = Polynomial(self.coeffs)
for i in range(self.degree - other.degree, -1, -1):
q.coeffs[i] = r.coeffs[other.degree + i] / other.coeffs[other.degree]
for j in range(other.degree + i, i - 1, -1):
r.coeffs[j] -= q.coeffs[i] * other.coeffs[j - i]
q.degree = len(q.coeffs) - 1
while q.degree > 0 and q.coeffs[q.degree] == 0:
q.degree -= 1
return q, r
def __str__(self):
return ' + '.join(['{}x^{}'.format(self.coeffs[i], i) for i in range(self.degree + 1)])
```
这个多项式类支持多种基本的操作,例如:
```python
p1 = Polynomial([1, 2, 3]) # 1 + 2x + 3x^2
p2 = Polynomial([4, 5]) # 4 + 5x
print(p1 + p2) # 5 + 7x + 3x^2
print(p1 - p2) # -3 - 3x + 3x^2
print(p1 * p2) # 4 + 13x + 22x^2 + 15x^3
print(p1 / p2) # (Polynomial: 0.375x + 0.25, Polynomial: -1.875)
```
当然,这只是一个简单的实现,还有很多可以改进的地方,例如增加异常处理、优化除法算法等。
阅读全文