page 1 of 9 ENCM 339 Fall 2017 Lecture Section 01 Lab 9 for the Week of November 20 Steve Norman Department of Electrical & Computer Engineering University of Calgary November 2017 Lab instructions and other documents for Section 01 of ENCM 339 can be found at http://people.ucalgary.ca/~norman/encm339fall2017/ Administrative details You may work individually or in pairs If you choose to work with a partner, it must be a student in the same lab section as you. Teams of two should hand in a single assignment, with both names printed clearly on the cover page. Important: Partners must make sure they both understand everything they hand in. You won t be allowed to work with a partner on Quiz 4 or the final exam! Lab 9 has the same Due Date pattern as Labs 1, 2, 4, 5 and 8 The Due Date for this assignment is 3:30pm Friday, November 24. The Late Due Date is 3:30pm Monday, November 27. The penalty for handing in an assignment after the Due Date but before the Late Due Date is 3 marks. In other words, X/Y becomes (X 3)/Y if the assignment is late. There will be no credit for assignments turned in after the Late Due Date; they will be returned unmarked. Marking scheme A B C D E total 6 marks 4 marks 2 marks 6 marks 10 marks 28 marks How to package and hand in your assignments Please see the information in the Lab 1 instructions, but also note that teams of two must put both names on the cover page.
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 2 of 9 Exercise A: Repeating Lab 5 Exercise D in Python Read This First: The format method of the str type Important note! Getting the appearance of numbers in program output exactly the way you want is satisfying and can often be an important factor in the usability of software you produce. However, with most languages and libraries, the rules for displaying numbers are complicated and huge in number. It doesn t make sense to commit such rules to memory unless it s part of your job to use knowledge of those rules many times every day. Quiz 4 and the Final Exam for Section 01 of ENCM 339 will NOT test you on the details of number formatting in C or Python! Some details You may have wondered whether it s possible to have Python insert values of variables into output in a way that s similar to use of printf or fprintf in C. In fact, there (at least) two different ways to do that, both of which create strings rather than directly doing output... Set up a string that looks very much like a control string for the C printf function, and then apply that to a tuple of numbers and/or strings using the % operator. Use the format method of the str type. In this course, we ll look only at the second approach, use of the format method. Here is a very simple example use of format that explains the basics: f = This course is {} {}: {}. s = f.format( ENCM, 339, Programming Fundamentals ) print(s) Each use of {} matches an argument in the method call. The program output is This course is ENCM 339: Programming Fundamentals. You can put numbers between { and } if you need to access arguments out of order, or access arguments more than once, as this silly example demonstrates: f = {0}, {1}.\nI repeat, {0}! print(f.format( Indentation must be perfect, students )) print() print(f.format( Know how a DFF behaves, digital designers )) The output is Indentation must be perfect, students. I repeat, Indentation must be perfect! Know how a DFF behaves, digital designers. I repeat, Know how a DFF behaves! You can also put information between { and } to control things like
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 3 of 9 minimum number of characters to use for a value; left-justification, right-justification, or centering; number of decimal places to use when displaying a float value; whether or not to use scientific notation when displaying a float value. Here s a little example: # right-justify, minimum width 20 f1 = The int value is {:>20}. # force scientfic notation, 4 digits after decimal point f2 = The float value is {:.4e}. # avoid scientfic notation, 25 digits after decimal point f3 = The float value is {:.25f}. my_int = 42 print(f1.format(my_int)) electron_charge = -1.60218e-19 print(f2.format(electron_charge)) print(f3.format(electron_charge)) The output is The int value is 42. The float value is -1.6022e-19. The float value is -0.0000000000000000001602180. For more information see Format Specification Mini-Language in the online Python Standard Library Reference. Read This Second For convenience, here is some text copied and pasted from the Lab 5 instructions: The fake course we ll consider has ten assignments, numbered 0 through 9. Maximum marks for the assignments are as follows: assignment 0 1 2 3 4 5 6 7 8 9 maximum marks 10 10 12 9 10 12 11 10 13 8 The sum of the maximum marks is 105. Normally, a student s overall assignment mark would therefore be the sum of their own assignment marks divided by 105, then multiplied by 100 to get a percentage. However, a student may have been excused from one or more assignments. In that case, it s not appropriate to divide by 105. For example, if a student were excused from Assignment 8, the overall assignment mark would be calculated as (sum of student s marks)/(105 13) 100%. A fake mark of 1.0 in the class record indicates that a student has been excused from an assignment. [... ] Here s an example of the expected format for a line of output, for a student who was excused from Assignments 5 and 6:
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 4 of 9 Jones, JJ 900123 71.5 / 82.0, 87.20% Download the file grades9a.py, read it, and run it. Then edit it as instructed in a comment near the end of the file. Hint: The split method of the str type will be helpful. Hand in printouts of your completed program and its output. Exercise B: A variation on Exercise A Repeat Exercise A, starting with the file grades9b.py. Hand in printouts of your completed program and its output. Exercise C: Functions as function arguments Read This First In Python it s easy to use the name of a function as an argument in a call to another function. Here s a very short demonstration: def triple(a): return 3 * a def quadruple(b): return 4 * b def foo(f, x): print( f of, x, is, f(x)) foo(triple, 5) foo(quadruple, 6) The program s output is f of 5 is 15 f of 6 is 24 In the first call to foo, the parameter f refers to triple, but in the second call to foo, f refers to quadruple. This exercise and Exercise D will present some practical uses for using function as function arguments. (By the way, it s possible to do similar things in C, but that requires learning the awkward syntax related to C pointer-to-function types)
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 5 of 9 Read This Second: The math module Some parts of the Python Standard Library, such as the print and len functions, are builtin they are always available, and you don t have to tell the interpreter where to find them. But most of the Python Standard Library is organized as a collection of modules. An important and useful library module for engineers is the math module, which provides mathematical functions such as sin, cos, tan, log (base e logarithm, usually written as ln in math textbooks) and log10 (base 10 logarithm); the best float approximations to some mathematical constants such as π and e, as variables. To use a module in a Python program, you must tell the interpreter to find it using an import statement. Here s how to import the math module: import math Once your program has imported a module, your program can access functions and variables from the module using the name of the module and a dot: import math print( cosine of pi/6 is, math.cos(math.pi / 6)) The output of the above program is cosine of pi/6 is 0.8660254037844387 Download the file tables9c.py, read it, and run it. Then add code to the program so that in addition to printing a table of the sine function, it prints tables of the cosine and tangent functions. You should not have to modify the make_table function in any way just add two new very simple function definitions and a few other simple lines of code. Hand in printouts of your completed program and its output. Exercise D: Approximate maximum of a math function Read This First Consider the problem of finding the maximum value of a mathematical function f(x), for all values of x in the interval described by a x b. If f is differentiable, it s often possible to find local minima and maxima of x by solving for x in f (x) = 0, where f is the derivative of f. However, sometimes the calculus for finding f and/or the algebra for solving f (x) = 0 can be messy! If only an approximate maximum is needed, it s often effective to look for the maximum among samples of f(x) taken at a finite number of values of x. This is illustrated in Figure 1 on page 6. Of course to get a better approximation to the maximum of f(x), you could take a number of samples that is much larger than 5!
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 6 of 9 Figure 1: Finding the approximate maximum of a function by sampling. In this example, samples of f(x) are taken at x = a, x = b, and 3 evenly-spaced values of x in between: x = a + 0.25 (b a), x = a + 0.5 (b a), and x = a + 0.75 (b a). The approximate maximum would in this case occur at x = a + 0.75 (b a), because f(a + 0.75 (b a)) is the largest sample. f(x) a b x Figure 2: Functions, intervals, and numbers of samples for Exercise D. n specifies the number of samples for values of x with a < x < b. Samples of f(x) with x = a and x = b should also be considered. So, for example, for the first row of the table, 101 samples should be taken. function a b n f(x) = x 2 + 1.43x 2.71 0 1 99 0 1 1,023 1 2 999 f(x) = 1 e 0.5x cos 2x 0 10 1,999 3 10 8,191 f(x) = 0.25x + sin 2x 0 3.5 2,799 4 10 5,999
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 7 of 9 Figure 3: Exercise E involves a simple electronic circuit with a voltage source, a resistor and a diode. V S + R V D + I Download the file approxmax9d.py, read it, and run it. Then edit the definition of approx_max so that it does what it is supposed to do; add code corresponding to the cases in the last six rows of the table in Figure 2 on page 6. (There is already code in place for the case given in the first row of the table.) For each case in the table, make sure that your program output is clear about which version of f is being considered, what the values of a and b are, and how many samples are to be taken. Hand in printouts of your completed program and its output. Exercise E: Fixed-point iteration Read This First In mathematics, a value of x that satifies the equation f(x) = x is called a fixed point of the function f. Fixed-point iteration is an algorithm that sometimes works well for finding fixedpoints. It s very simple: Start with x 0, an initial guess at the fixed point, and then do the following sequence of updates: x 1 = f(x 0 ), x 2 = f(x 1 ), x 3 = f(x 2 ),... If the iteration works, the sequence x 0, x 1, x 2,... will converge to a solution of f(x) = x. (Whether or not the sequence converges depends on how close x 0 is to the fixed-point and some mathematical properties of the function f.) Read This Second Figure 3 is a diagram for a circuit involving two things you should recognize from ENGG 225 and a device called a diode. A diode has this important and useful behaviour: If the voltage V D is positive, the current I will be positive and significant in magnitude. If V D is negative, I will be negative but extremely close to zero.
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 8 of 9 For some calculations, the Shockley diode equation is a reasonable model for a diode: ( ) I = I S e V D nv T 1 (1) I S, the reverse-bias saturation current and n, the ideality factor, are properties that vary from one diode to another. V T, the thermal voltage, is independent of diode design and construction but is temperature-dependent. At room temperature, V T 25.85 mv. Suppose that for the circuit of Figure 3, V S, R, I S and n are all known, and we want to solve for I and V D. Ohm s law and Kirchoff s voltage law together say that I = V S V D R Together equations (1) and (2) give us two equations in two unknowns. solve (1) for V D. First let s rearrange it: (2) Let s e V D nv T = I + I S I S Next, take logarithms on both sides: ( ) V D I + IS = ln nv T Rearrange again: I S ( ) I + IS V D = nv T ln If we plug that expression for V D into (2), we get: ( ) I+I V S nv T ln S I S I = R That looks scary algebraically is it even possible to solve for I? But notice that the equation is of the form I = f(i) maybe fixed-point iteration with a computer can give us a numerical solution! It turns out that it s essentially impossible to get a voltage of more than about V D = +0.7 V across a typical silicon diode, so if V D is significantly larger than 0.7 V, a good initial guess at I for fixed-point iteration is simply I V S /R. Write a Python program that uses fixed-point iteration to solve for I and V D in the circuit of Figure 3, operating at room temperature. With the initial guess suggestion given above, ten iterations of I n+1 = f(i n ) are more than enough to get numbers that are accurate to many significant digits. Your program should solve for I and V D for all the variations of the problem given in this table: V S R I S n 10.0 V 1.0 kω 20 na 1.95 5.0 V 2.2 kω 20 na 1.95 2.5 V 2.2 kω 20 na 1.95 15.0 V 10.0 kω 35 na 1.95 3.0 V 10.0 kω 35 na 1.95 You are free to organize your program however you like, but please try hard I S (3)
ENCM 339 Fall 2017 Lecture Section 01 Lab 9 page 9 of 9 to make the code as easy-to-read as possible for the TA s who will be marking it; to make the output of your program easy-to-read for an electrical engineer who has no idea how to read Python code. Hand in printouts of your program and its output.