Download presentation
Presentation is loading. Please wait.
1
Recitation 7 Programming for Engineers in Python
2
Plan Plotting Debugging The Code 2
3
Plotting - Example 3
4
Plotting 4 To install matplotlib package, just click matplotlib downloadmatplotlib 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
5
Plotting 5 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]
6
Line Styles 6 The entire description
7
Plot Continuous Values 7 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! import numpy as np x = np.arange(0, 5, 0.1)
8
Numpy Arrays - Creation 8 >>> 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.]])
9
Numpy Arrays 9 >>> 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])
10
Numpy Arrays - Arithmatics 10 >>> 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]])
11
Plot Continuous Values 11 Left plt.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')
12
Explaining the Data 12 How can I know what a plot refers to? plt.xlabel(‘radians’) plt.ylabel(‘cosine’) plt.title(‘Cosine Function’)
13
Subplots 13
14
Subplots 14 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') Plot 1Plot 2 Plot 3Plot 4 Plot 5Plot 6
15
Show Histograms 15 # 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])
16
Show Histograms 16
17
∏ Estimation 17 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) return summ
18
∏ Estimation 18 Create estimations of π by different error values pi_est = [] err_val = range(2, 12) err_vec = [10**(-x) for x in err_val] for err in err_vec: pi_est.append(estimate_pi(err))
19
∏ Estimation – Build Plot 19 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')
20
∏ Estimation - Result 20
21
How to Find Bugs 21
22
22 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
23
23 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 in range(nPlayers): for card in range(nCards): # create one guess cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list)
24
How to Find Bugs 24 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
25
25 Trace the code step by step. In this case – by iterations. We begin by tracing the outer loop: for player in range(3): # 1000 is a lot! for card in range(nCards): cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list) print cards_list How to Find Bugs
26
26 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
27
27 Ok, we found the problem, but what is the reason? And the solution? Main suspect: players_guess.append(cards_list) Is this drawing correct? How to Find Bugs players_guess cards_list
28
28 There is only one list – which is mutated every iteration. Found the problem. Solution? players_guess cards_list How to Find Bugs
29
29 for player in range(nPlayers): # create cards list inside the loop cards_list=[0]*nCards for card in range(nCards): cards_list[card]= random.randrange(0,nSuits) players_guess.append(cards_list) How to Find Bugs
30
30 Mission: replace first and last character in a string def switch(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
31
31 Add ‘print’ def switch(s): first = s [0] last = s [-1] s = s.replace(s[0], last ) s = s.replace(s[-1], first ) return s How to Find Bugs
32
32 >>> 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
33
33 >>> switch('abcd') abcd dbcd 'abca' >>> switch('banana') banana aanana 'bbnbnb‘ Observations? How to Find Bugs
34
34 Observation: replace changes all occurances 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
35
35 >>> 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
36
36 New code: return s[-1]+s[1:-1]+s[0] >>> switch('abcd') 'dbca' >>> switch('banana') 'aananb’ How to Find Bugs
37
37 class Nothing: def set_value(self, value): self.value = value def print_value(value): print value not_a_thing = Nothing() not_a_thing.set_value(“nowhere”) not_a_thing.print_value() >>> ??? How to Find Bugs
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.