Vectorize a class for polynomials Introducing an array instead of a list in class Polynomial, as suggested in Exercise 7.26, does not enhance the implementation. A real enhancement arise when the code...


Vectorize a class for polynomials


Introducing an array instead of a list in class Polynomial, as suggested in Exercise 7.26, does not enhance the implementation. A real enhancement arise when the code is vectorized, i.e., when loops are replaced by operations on whole arrays.


First, vectorize the __add__ method by adding the common parts of the coefficients arrays and then appending the rest of the longest array to the result (appending an array a to an array b is done by concatenate(a, b)).


Second, vectorize the __call__ method by observing that evaluation of a polynomial, Pn−1
i=0
cix i , can be computed as the inner product of two arrays: (c0, . . . , cn−1) and (x
0
, x1
, . . . , xn−1
). The latter array can be computed by x**p, where p is an array with powers 0, 1, . . . , n − 1.


Third, the differentiate method can be vectorized by the statements


n = len(self.coeff) self.coeff[:-1] = linspace(1, n-1, n-1)*self.coeff[1:] self.coeff = self.coeff[:-1]


Show by hand calculations in a case where n is 3 that the vectorized statements produce the same result as the original differentiate method.


The __mul__ method is more challenging to vectorize so you may leave this unaltered. Check that the vectorized versions of __add__, __call__, and differentiate work by comparing with the scalar code from Exercise 7.26 or the original, list-based Polynomial class. Name of program file: Polynomial_array2.py.

Nov 19, 2021
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here