370 likes | 517 Views
Programming for Engineers in Python. Recitation 7. Plan. Plotting Debugging The Code. Plotting - Example. Plotting. To install matplotlib package, just click matplotlib download Simple example import matplotlib.pyplot as plt # shorten the module’s name plt.plot ([1,2,3,4])
E N D
Programming for Engineers in Python Recitation 7
Plan • Plotting • Debugging The Code
Plotting • To install matplotlib package, just click matplotlib download • Simple example import matplotlib.pyplot as plt# shorten the module’s name plt.plot([1,2,3,4]) plt.ylabel(‘some numbers') plt.show(False) # False is required when calling ‘show’ from the shell • A list represents a vector! • A single input list = y values • x vector - from 0
Plotting • Create square numbers plt.plot([1,4,9,16]) • Choose correct x values – two lists! plt.plot([1,2,3,4], [1,4,9,16], ‘ro’) • Fix ranges of axes plt.axis([0, 6, 0, 20]) • Order: [xmin, xmax, ymin, ymax]
Line Styles The entire description
Plot Continuous Values • Show cos(x) of x values 0-5, with 0.1 step size. How is this range created? >>> range(0, 5, 0.1) TypeError: range() integer step argument expected, got float. • Use numpy! importnumpy as np x = np.arange(0, 5, 0.1)
Numpy Arrays - Creation >>> A= np.array([[1, 2, 4, 8], [16, 32, 64, 128]]) # 2x4 matrix array([[1, 2, 4, 8], [16, 32, 64, 128]]) >>> B= np.arange(8).reshape(2, 4) # reshaped into 2x4 matrix array([[0, 1, 2, 3], [4, 5, 6, 7]]) >>> np.zeros((2, 4)) # create a 2x4 matrix of zeros array([[0., 0., 0., 0.], [0., 0., 0., 0.]])
Numpy Arrays >>> np.ones((2, 4)) # create a 2x4 matrix of ones array([[1., 1., 1., 1.], [1., 1., 1., 1.]]) >>> A– B # elementwise subtraction array([[1, 1, 2, 5], [12, 27, 58, 121]]) >>> B**2 array([[0, 1, 4, 9], [16, 25, 36, 49])
Numpy Arrays - Arithmatics >>> A*B # elementwise product array([[ 0, 2, 8, 24], [ 64, 160, 384, 896]]) >>> np.dot(A, np.transpose(B)) # dot product, dims must agree array([[ 34, 94], [ 544, 1504]]) >>> B.cumsum(axis=1) # cumulative sum along each row array([[ 0, 1, 3, 6], [ 4, 9, 15, 22]])
Plot Continuous Values Leftplt.plot(x, np.cos(2*np.pi*x), 'r--') Right x1 = np.arange(0, 10, 0.1) x2 = np.arange(0, 10) plt.plot(x1, np.exp(x1), 'b-', x2, np.exp(x2), 'ro')
Explaining the Data • How can I know what a plot refers to? plt.xlabel(‘radians’) plt.ylabel(‘cosine’) plt.title(‘Cosine Function’)
Subplots • subplot(numRows, numCols, plotNum) >>> subplot(3, 2, 4) Lose the commas if rows and cols < 10 plt.subplot(211) plt.plot(x, np.cos(2*np.pi*x), 'r--') plt.subplot(212) x1 = np.arange(0, 10, 0.1) x2= np.arange(0, 10) plt.plot(x1, np.exp(x), 'b-', x2, np.exp(x2), 'ro')
Show Histograms # create data mu = 100 sigma = 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data plt.hist(x, 50, normed = 1, facecolor='g') # arrange plot plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.axis([40, 160, 0, 0.03])
∏ Estimation • Rings a bell? (recitation 4) def estimate_pi(error): term = 1 summ = 0 k = 1 while term > error: term = 1.0/k**2 summ += term k += 1 summ = sqrt(summ*6.0) returnsumm
∏ Estimation • Create estimations of π by different error values pi_est = [] err_val = range(2, 12) err_vec = [10**(-x) for x inerr_val] forerr inerr_vec: pi_est.append(estimate_pi(err))
∏ Estimation – Build Plot margin = 0.01 plt.plot([err_val[0]-1, err_val[-1]+1],[pi, pi], 'b-', err_val, pi_est, 'go') plt.axis([err_val[0]-1, err_val[-1]+1, min(pi_est)- margin, max(pi_est)+ margin ]) # document plot plt.xlabel('-log10 error') plt.ylabel('Estimation') plt.title('Pi Estimation') plt.legend(('python pi','estimation'), loc=4) # show plot and save as an image plt.show() plt.savefig('pi.png')
How to Find Bugs • We refer to semantic (not syntactic) bugs • General Scheme: • Think • Investigate variables through the interactive mode (shell) Or • Add “print” statements inside functions Tip: reduce the problem - fewer loop iterations, toy data structures, isolate parts of the code etc. Runs faster, helps tracing problems.
How to Find Bugs • A unit is the smallest testable part of an application. • The goal of unit testing is to isolate each part of the program and show that the individual parts are correct • Pros: simplifies integration with other units, “living documentation” (how to use the code), helps design. • The hw tests are examples of unit testing
How to Find Bugs • Mission: create 1000 lists of 25 guesses (random numbers) from 0,1,2,3 nSuits, nCards, nPlayers = 4, 25, 1000 players_guess=[] cards_list=[0]*nCards # create guesses for player inrange(nPlayers): for card inrange(nCards): # create one guess cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list)
How to Find Bugs How to Find Bugs Investigate the lists created: >>> players_guess[0] [1, 1, 3, 3, 2, 2, 2, 3, 1, 2, 3, 1, 3, 0, 0, 3, 2, 0, 2, 0, 3, 2, 2, 3, 2] >>> players_guess[1] [1, 1, 3, 3, 2, 2, 2, 3, 1, 2, 3, 1, 3, 0, 0, 3, 2, 0, 2, 0, 3, 2, 2, 3, 2] >>> players_guess[2] [1, 1, 3, 3, 2, 2, 2, 3, 1, 2, 3, 1, 3, 0, 0, 3, 2, 0, 2, 0, 3, 2, 2, 3, 2] Oh, No, Bug!
How to Find Bugs • Trace the code step by step. • In this case – by iterations. We begin by tracing the outer loop: for player inrange(3): # 1000 is a lot! forcard inrange(nCards): cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list) printcards_list
How to Find Bugs Output: [2, 3, 3, 0, 2, 1, 2, 0, 2, 3, 2, 2, 2, 1, 1, 0, 0, 2, 2, 1, 2, 3, 0, 0, 3] [1, 2, 3, 3, 2, 0, 0, 1, 0, 0, 1, 2, 2, 3, 3, 1, 2, 1, 0, 0, 2, 0, 1, 3, 3] [2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1] The problem is not here. What is players_guess? >>> players_guess [[2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1] , [2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1] , [2, 2, 2, 0, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 1, 2, 1, 1, 0, 1, 2, 2, 0, 2, 1]] Notice anything?
How to Find Bugs • Ok, we found the problem, but what is the reason? And the solution? • Main suspect: players_guess.append(cards_list) Is this drawing correct? cards_list players_guess cards_list cards_list
How to Find Bugs • There is only one list – which is mutated every iteration. • Found the problem. Solution? cards_list players_guess cards_list cards_list
How to Find Bugs for player inrange(nPlayers): # create cards list inside the loop cards_list=[0]*nCards for card inrange(nCards): cards_list[card]= random.randrange(0,nSuits) players_guess.append(cards_list)
How to Find Bugs • Mission: replace first and last character in a string defswitch(s): first = s [0] last = s [-1] s = s.replace(s[0], last ) s = s.replace(s[-1], first ) return s >>> switch(‘abcd’) abca >>> switch(‘banana’) bbnbnb
How to Find Bugs • Add ‘print’ defswitch(s): first = s [0] last = s [-1] s = s.replace(s[0], last ) s = s.replace(s[-1], first ) returns
How to Find Bugs >>> switch('abcd') 'abca' >>> switch('banana') 'bbnbnb‘ • Let’s add ‘print’ commands inside switch: print s s = s.replace(s[0], last ) print s s = s.replace(s[-1], first ) return s
How to Find Bugs >>> switch('abcd') abcd dbcd 'abca' >>> switch('banana') banana aanana 'bbnbnb‘ • Observations?
How to Find Bugs • Observation: • replace changes alloccurances of the character in the string – we only want one specific change. >>> help(str.replace) replace(...) S.replace(old, new[, count]) -> string Solution: s = s.replace(s[0], last, 1 ) s = s.replace(s[-1], first, 1 )
How to Find Bugs >>> switch('abcd') abcd dbcd 'abcd' >>> switch('banana') banana aanana 'banana‘ Observation: The first letter is changed twice! Solution: replace doesn’t work for us, use a different method!
How to Find Bugs New code: return s[-1]+s[1:-1]+s[0] >>> switch('abcd') 'dbca' >>> switch('banana') 'aananb’
How to Find Bugs classNothing: defset_value(self, value): self.value = value defprint_value(value): print value not_a_thing = Nothing() not_a_thing.set_value(“nowhere”) not_a_thing.print_value() >>> ???