# Programming for Engineers in Python

• View
41

0

Embed Size (px)

DESCRIPTION

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]) - PowerPoint PPT Presentation

### Text of Programming for Engineers in Python

PowerPoint Presentation

Recitation 7

Programming for Engineers in Python1PlanPlottingDebugging The Code22

Plotting - Example3

Simple exampleimport matplotlib.pyplot as plt # shorten the modules nameplt.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 valuesx vector - from 0

4Plotting5Create square numbersplt.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 axesplt.axis([0, 6, 0, 20])Order: [xmin, xmax, ymin, ymax]

5Line Styles6

The entire description6Plot Continuous Values7Show 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)

7Numpy Arrays - Creation8>>> A= np.array([[1, 2, 4, 8], [16, 32, 64, 128]]) # 2x4 matrixarray([[1, 2, 4, 8], [16, 32, 64, 128]])>>> B= np.arange(8).reshape(2, 4) # reshaped into 2x4 matrixarray([[0, 1, 2, 3], [4, 5, 6, 7]])>>> np.zeros((2, 4)) # create a 2x4 matrix of zerosarray([[0., 0., 0., 0.], [0., 0., 0., 0.]])8Numpy Arrays9>>> np.ones((2, 4)) # create a 2x4 matrix of onesarray([[1., 1., 1., 1.], [1., 1., 1., 1.]])>>> A B # elementwise subtractionarray([[1, 1, 2, 5], [12, 27, 58, 121]])>>> B**2array([[0, 1, 4, 9], [16, 25, 36, 49])

9Numpy Arrays - Arithmatics10>>> A*B # elementwise product array([[ 0, 2, 8, 24], [ 64, 160, 384, 896]])>>> np.dot(A, np.transpose(B)) # dot product, dims must agreearray([[ 34, 94], [ 544, 1504]])>>> B.cumsum(axis=1) # cumulative sum along each row array([[ 0, 1, 3, 6], [ 4, 9, 15, 22]])

10Plot Continuous Values11Left 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')

11Explaining the Data12How can I know what a plot refers to?plt.xlabel(radians)plt.ylabel(cosine)plt.title(Cosine Function)

12Subplots13

13Subplots14subplot(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 2Plot 3Plot 4Plot 5Plot 614Show Histograms15# create datamu = 100sigma = 15x = mu + sigma * np.random.randn(10000)# the histogram of the dataplt.hist(x, 50, normed = 1, facecolor='g')# arrange plotplt.xlabel('Smarts')plt.ylabel('Probability')plt.title('Histogram of IQ')plt.axis([40, 160, 0, 0.03])

15Show Histograms16

16 Estimation17Rings 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 summ17 Estimation18Create estimations of by different error valuespi_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))

18 Estimation Build Plot19margin = 0.01plt.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 plotplt.xlabel('-log10 error')plt.ylabel('Estimation')plt.title('Pi Estimation')plt.legend(('python pi','estimation'), loc=4)# show plot and save as an imageplt.show()plt.savefig('pi.png')

19 Estimation - Result20

20How to Find Bugs21We refer to semantic (not syntactic) bugs

General Scheme:ThinkInvestigate variables through the interactive mode (shell)OrAdd 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.

2122A 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 correctPros: 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

22How to Find Bugs23Mission: create 1000 lists of 25 guesses (random numbers) from 0,1,2,3nSuits, nCards, nPlayers = 4, 25, 1000players_guess=[]cards_list=[0]*nCards# create guessesfor player in range(nPlayers): for card in range(nCards): # create one guess cards_list[card ]= random.randrange(0,nSuits) players_guess.append(cards_list)

23How to Find Bugs24Investigate 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

2425Trace 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

2526Output:[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

2627Ok, 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_guesscards_listcards_listcards_list2728There is only one list which is mutated every iteration.Found the problem.Solution?players_guesscards_listcards_listcards_listHow to Find Bugs

2829for 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

2930Mission: replace first and last character in a stringdef 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

3031Add printdef 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

3132>>> switch('abcd')'abca'>>> switch('banana')'bbnbnb

Lets add print commands inside switch:print ss = s.replace(s[0], last )print ss = s.replace(s[-1], first )return s

How to Find Bugs

3233>>> switch('abcd')abcddbcd'abca'>>> switch('banana')bananaaanana'bbnbnbObservations?How to Find Bugs

3334Observation: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

3435>>> switch('abcd')abcddbcd'abcd'>>> switch('banana')bananaaanana'bananaObservation: The first letter is changed twice!Solution: replace doesnt work for us, use a different method!How to Find Bugs

3536New code:return s[-1]+s[1:-1]+s[0]

>>> switch('abcd')'dbca'>>> switch('banana')'aananbHow to Find Bugs

3637class Nothing:def set_value(self, value): self.value = valuedef print_value(value): print value

not_a_thing = Nothing()not_a_thing.set_value(nowhere)not_a_thing.print_value()>>> ???How to Find Bugs

37

Documents
Software
Education
Documents
Software
Documents
Software
Technology
Education
Technology
Engineering
Software