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

Create a script file that does the following: * Use a for loop over a range of v

ID: 3671364 • Letter: C

Question

Create a script file that does the following:

* Use a for loop over a range of values of n (n = 4, 8, 16,…, 2^12)

* For each value of n: create a random matrix (size n by n) and a random vector (size n)

* For each value of n: Use your function from problem #4 to compute the matrix-vector product Ax while using the tic/toc commands to time the calculation.

* Plot the results: x-axis is the values of n used in your calculations. y-axis is the time needed to perform each calculation (depends on n). Normalize this curve so the maximum value is 1 (i.e. divide the “y values” that you plot by their max value).

* Plot a second curve on this figure that shows how the number of flops for this calculation grows with n (see lecture notes or page 371 of textbook). You will also want to normalize this curve so it has a max value of 1.

Explanation / Answer

import time
import random
import matplotlib.pyplot as plt
def matmult(m, v):
    nrows = len(m)
    w = [None] * nrows
    for row in range(nrows):
        w[row] = reduce(lambda x,y: x+y, map(lambda x,y: x*y, m[row], v))
    return w

#................................................
if __name__=='__main__':
    N = [2**i for i in range (2,13)]
    time_taken = []
    flops = []
    max_time = 0
    for item in N:
        vec = [random.random() for i in range(1, item+1)]
        mat = [[random.random() for e in range(item)] for e in range(item)]
        #print 'vec=', vec
        #print 'mat=', mat
        tic = time.time()
        #print 'mat . vec=', matmult(mat, vec)
        toc= time.time()
        time_taken.append(toc-tic)
        if toc-tic > max_time:
       max_time = toc-tic
        flops.append(float(item*item)/(2**24))
    for item in range(0,len(time_taken)):
   time_taken[item] = time_taken[item]/max_time
    plt.subplot(211)
    plt.plot(N,time_taken)
    plt.title('Time taken per n',fontweight='bold')
    plt.ylabel('time in sec',fontweight='bold')
    plt.xlabel('value of n',fontweight='bold')
    plt.subplot(212)
    plt.plot(N,flops)
    plt.title('Flops per n',fontweight='bold')
    plt.ylabel('total flops',fontweight='bold')
    plt.xlabel('value of n',fontweight='bold')
    plt.show()

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote