import numpy as np def polym(c, x): # this function evaluates c[0] + c[1]*x + ..
ID: 3603144 • Letter: I
Question
import numpy as np
def polym(c, x):
# this function evaluates c[0] + c[1]*x + ... c[m]*x**m by summing term by term,
# it computes x**i at the i-th iteration (the slowest of all of the three methods)
#
#make sure x is an np array so that it can be scaled (i.e., x*x will be x**2 elementwisely)
def polym2(c, x):
# this function evaluates c[0] + c[1]*x + ... c[m]*x**m by summing term by term,
# it should not compute x**i directly at each iteration, instead it should update
# x**i as x**(i-1)*x, reusing the x**(i-1) that is already computed at the previous iteration
#
#make sure x is an np array so that it can be scaled (i.e., x*x will be x**2 elementwisely)
#(also, be careful when copying an np array, if not done properly, it would be hard to debug)
def horner(c, x):
# this function evaluates c[0] + c[1]*x + ... c[m]*x**m by the Horner's method.
#make sure x is an np array so that it can be scaled (i.e., x*x will be x**2 elementwisely)
def compare_efficiency():
import time
print(' ==> Now compare the efficiency of the methods: ')
mmin=4000; mmax=20000; step=2000
#initialize lists to store the time for each method
time_poly=[]; time_poly2=[]; time_horner=[]
for m in range(mmin, mmax, step):
c = np.random.randn(m)
x = np.random.randn(round(m/4));
x /= max(abs(x))
#using the above generated x and c,
#add code below to call the three functions above, find the excution time for each,
#and store the time in the corresponding lists
#add code to print out the timing info using the format specified in the project PDF file
x= range(mmin, mmax, step)
#add code below to plot the figure using the format specified in the project PDF file
#add code save the plot into a file naed 'poly_eval_compare.png' for submission
Any help please.
Explanation / Answer
# this function evaluates c[0] + c[1]*x + ... c[m]*x**m by summing term by term,
# it computes x**i at the i-th iteration (the slowest of all of the three methods)
#
#make sure x is an np array so that it can be scaled (i.e., x*x will be x**2 elementwisely)
def polym2(c, x):
# this function evaluates c[0] + c[1]*x + ... c[m]*x**m by summing term by term,
# it should not compute x**i directly at each iteration, instead it should update
# x**i as x**(i-1)*x, reusing the x**(i-1) that is already computed at the previous iteration
#
#make sure x is an np array so that it can be scaled (i.e., x*x will be x**2 elementwisely)
#(also, be careful when copying an np array, if not done properly, it would be hard to debug)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.