Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Polynomial:
- def __init__(self, coefficients):
- self.coeffs = []
- for item in coefficients:
- item = float(item)
- self.coeffs.insert(0, item)
- # list of coefficients is in ascending power
- self.length = len(self.coeffs)
- def __str__(self):
- string = ''
- coeffs = self.coeffs
- coeffs.reverse()
- i = self.length - 1
- for coeff in coeffs:
- if i != (self.length - 1 or coeff > 0):
- string += ' + '
- if i == 0:
- string += (str(coeff))
- elif i == 1:
- string += (str(coeff) + ' x ')
- elif coeff == 0:
- pass
- else:
- string += (str(coeff) + ' x**' + str(i))
- i -= 1
- return string
- def coeff(self, i):
- return self.coeffs[i]
- def add(self, other):
- if self.length > other.length:
- shorter = other.coeffs
- longer = self.coeffs
- else:
- shorter = self.coeffs
- longer = other.coeffs
- i = 0
- sumPoly = []
- while i < len(shorter):
- sumPoly.append(shorter[i] + longer[i])
- i += 1
- while i < len(longer):
- sumPoly.append(longer[i])
- i += 1
- sumPoly.reverse()
- poly = Polynomial(sumPoly)
- return poly
- def mul(self, other):
- i = 0
- product = Polynomial([])
- for item1 in self.coeffs:
- new_list = []
- n = i
- # if item is coef. to x^power, move values up list
- while i > 0:
- new_list.append(0)
- i -= 1
- for item2 in other.coeffs:
- new_list.append(item1*item2)
- i = n + 1
- new_list.reverse()
- # for each iteration, add produced polynomial to product
- newPoly = Polynomial(new_list)
- product = product.add(newPoly)
- return product
- def val(self, v):
- value = 0
- for exp in range(0, self.length):
- value += self.coeffs[exp]*(v**exp)
- return value
- def roots(self):
- def root(x, y):
- if det < 0:
- roots = [(complex(x, y)), (complex(x, -y))]
- elif det == 0:
- roots = [x]
- else:
- roots = [(x + y), (x - y)]
- return roots
- if self.length == 2:
- c = self.coeffs[0]
- b = self.coeffs[1]
- roots = [-c/b]
- return roots
- elif self.length == 3:
- a = self.coeffs[2]
- b = self.coeffs[1]
- c = self.coeffs[0]
- det = b**2 - 4*a*c
- y = (abs(det)**0.5)/(2*a)
- x = -b/(2*a)
- return root(x, y)
- else:
- return 'Error! First or second order polynomials only.'
- def __add__(self, other):
- return self.add(other)
- def __mul__(self, other):
- return self.mul(other)
- def __call__(self, x):
- return self.val(x)
- def __repr__(self):
- return str(self)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement