For exercise we should create a class Polynomials, which stores the coefficients of a Polynomial of one variable (1 dimensional), implementing the print function, multiplication, sum and subtraction of two polynomials, the evaluation in one point as a functor and two methods implementing the derivative and the integral of the polynomial(integration constants set to zero).
I tried to create a Class Polynomials, where I can create a Polynomial with n coefficients and implemented the methods.
When I don't use an extra class and create Polynomials like p1 = np.poly1d([...])
, the code just works fine. But as soon as I create the class Polynomials
and use my __init__
function, the code shows several errors, when calling other methods.
Whether it's Key errors or Polynomials object has no attribute '_variable'
My Code:
import numpy as np
class Polynomials (np.poly1d):
def __init__(self, coefficients):
self.name = np.poly1d(coefficients)
def Coefficients(self):
return self.c
def evaluation(self, x):
return self(x)
def mul(self, a):
return np.polymul(self, a)
def sum(self, a):
return np.polyadd(self, a)
def subtraction(self, a):
return np.polysub(self, a)
def __str__(self):
return str(self.name)
def differentiate(self):
return np.polyder(self)
def integrate(self):
return np.polyint(self)
a= Polynomials([2,5,7,8])
b = Polynomials([3,5,7,1])
print (a)
print(b)
#print(a(10))
c = a.mul(b)
#print(c)
Error code looks like:
line 14, in mul
return np.polymul(self, a)
File "<__array_function__ internals>", line 6, in polymul
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numpy/lib/polynomial.py", line 904, in polymul
a1, a2 = poly1d(a1), poly1d(a2)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site- packages/numpy/lib/polynomial.py", line 1155, in __init__
self._variable = c_or_r._variable
AttributeError: 'Polynomials' object has no attribute '_variable'
I already tried to test, what object I really create there with print(isinstance(a, np.poly1d))
, which shows true, when I create the polynomial within the new class AND when I create it without the Class.
So, why can I perform all operations with the created polynomial, when I create it without the class and can't perform it, when I create it in the class? Where am I lost?
Try this:
class Polynomials (np.poly1d):
def __init__(self, coefficients):
super().__init__(coefficients)
self.name = np.poly1d(coefficients)
# ...
Otherwise you never run any of the poly1d
initialisation procedures.