Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please answer this question with Python or matlab codes! Thank you! Later in the

ID: 2247077 • Letter: P

Question

Please answer this question with Python or matlab codes! Thank you!

Later in the class, we will use polynomials for a number of things including interpolation numeric integration, etc. A polynomial of order N can be written as p(x) = a_0 + a_1 x + a_2 x^2 + .. + a_N x^N = sigma^N_i = 0 a_i x^I where a: are the polynomial coefficients For example, the polynomial y = 3x^2 + 5 has coefficients a_0 = 5, a_1 = 0 and a_2 = 3. 1. Create a function in Matlab or Python that takes a vector of polynomial coefficients and a function value and returns the value of the polynomial. You do not need to submit a report for this problem - only your Matlab or Python files.

Explanation / Answer

# calculates polynomial value

import numpy as np

def polynomial_value(coefs, x):
   result = 0.0

   for i in range(0, len(coefs)):
       term = coefs[i] * pow(x, i) # calculate the term
       result = result + term # update the result

   return result

if __name__ == '__main__':
   # test the function
   y = polynomial_value([1,0.5,3], 10)
   print ('The result from using polynomial_value = {0:.3f}'.format(y))

   y = np.polyval([3,0.5,1], 10) # order is opposite as stated in question
   print ('The result from using polyval function = {0:.3f}'.format(y))

OUTPUT:

The result from using polynomial_value = 306.000
The result from using polyval function = 306.000

---------

I have written the code in python3. If you are using python2, then there needs to be slight modification with the print statement. Let me know if you are using python2 in the comments. Thank you.