Please complete these assignments. The directions are fairly straight forward.
1 Arithmetic operators These are the built-in arithmetic operators of Python. +, −, ∗, /: Usual addition, subtraction, multiplication and division. a ∗ ∗b: ab a%b: Remainder operator. Returns the remainder of ab . 2 Arrays and matrices In many computer programs, the best way to handle a mathematical problem is by using vectors and matrices. Python has built-in structures called lists, tuples and dictionaries that are similar to vectors and matrices but Python is not really good at doing mathematics on them. They are more for saving and sorting data and therefore, essential parts of data mining. We will not cover these but if you are interested, here is a great article to read. So what do we use? We often rely on arrays and matrices but these are not built-in structures of Python, they are parts of NumPy package (which means you need to import NumPy first!) 2.1 NumPy Arrays Let’s create 3 by 1 matrices. from numpy import * u = array ( [ 1 , 2 , 3 ] ) v = array ( [ 4 , 5 , 6 ] ) What’s interesting about arrays in Python is that all basic arithmetic operators between arrays are done component- wise. u+v: array([5, 7, 9]) u-v: array([-3, -3, -3]) u*v: array([4, 10, 18]) u/v: array([0.25, 0.4, 0.5]) u**v: array([1, 32, 729]) To see a certain element, you can do ‘u[n]’ and it will show you n-th element of u. It’s important note that the first element is 0-th element! To create a multi-dimensional array, we can do the following. u = array ( [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] ] ) v = u . t ranspose ( ) u is a 3 by 2 array and v is a transpose of u, therefore, a 2 by 3 array. Now that they have different dimensions, Python can’t do component-wise computation between u and v. Indeed, if you try something like u + v, Python will return an error. Traceback ( most r e c ent c a l l l a s t ) : F i l e ”
” , l i n e 1 , in u+v ValueError : operands could not be broadcast toge the r with shapes (3 , 2 ) (2 , 3 ) If you want to do the usual matrix multiplications between them, you can use dot function or matmul function, @(matmul function is available only for version ≥ 3.5). w = dot (u , v ) z = u@v 1 https://physics.nyu.edu/pine/pymanual/html/chap3/chap3_arrays.html both return the same 3 by 3 matrix. In order to pick out certain element, you simply do u[n][m] which will return the element of n-th column and m-th row. If you want to extract an entire row, type u[:][m] and similarly for an entire column, u[n][:]. Here are some other useful functions, all from NumPy package. u[n][m]=x: set n,m element to be x. u.shape: dimension of u, (n, m). zeros((n, m)): create an n by m zero matrix. ones((n,m)): create an n by m one matrix. eye(n): create an n by n identity matrix. 2.2 NumPy Matrices NumPy also has a class called ‘matrix’ which is a subclass of n-dimensional array. Matrices in NumPy are strictly 2-dimensional. There were certain advantages of matrices in older versions of Python especially before 3.5 when matmul function didn’t exist. However, there is little to no reason to use matrix over array anymore so we will not go over this in any detail. You can read more about the differences between matrices and arrays here 3 Data types II When you do zeros((2,2)) you will get array ( [ [ 0 . , 0 . , 0 . ] , [ 0 . , 0 . , 0 . ] ] ) Why do we have ‘0.’ instead of ‘0’? ‘.’ is a decimal point, signifying that what you have is a float rather than an integer. So why does this matter? Let’s say we created the following array. u = array ( [ [ 1 , 1 ] , [ 1 , 1 ] ] ) This defines a 2 by 2 one matrix, each entry being an integer 1 rather than a float 1.0. The problem was, in older versions of Python, an array could only have one type of element in it. That is, once you create an integer array, everything needs to be stay as an integer. That means if you do u [ 0 ] [ 0 ] = pi the first element of u becomes the integer part of π, which is 3, rather than 3.14 · · · . This problem was solved in Python 3 by letting array have multiple data types in it and we don’t need to worry about it anymore but it’s something worth noting in case you need to deal with older versions. 4 Assignment 1. Create two 3 by 2 arrays, u and v. 2. Calculate w = u ∗ vT . 3. Take a screenshot and upload it in Blackboard. 2 https://stackoverflow.com/questions/4151128/what-are-the-differences-between-numpy-arrays-and-matrices-which-one-should-i-u Arithmetic operators Arrays and matrices NumPy Arrays NumPy Matrices Data types II Assignment 1 Functions When we define a new function, we can save the script and import it like we import packages. For example, if I define a function ‘f(x)’ in a file called ‘function1.py’, then I can import it and use it by import f unc t i on1 func t i on1 . f ( 2 ) It’s important to note that just like in MATLAB, the script you want to import should be in the current working directory. However, seeing and changing current working directory in Python is not as intuitive as it is in MATLAB import os ###package c a l l e d os i s needed os . getcwd ( ) ###pr in t current working d i r e c t o r y os . chd i r ( ” newdir ” ) ###change the d i r e c t o r y Also, if you make a change to the file you imported, you need to reload the file to apply the changes. You can simply type from impor t l i b import reload reload ( func t i on1 ) However, there is an important thing to note. If you loaded the module by typing ‘from function1 import*’, then you won’t be able to use reload function. Also, if you used ‘import function1 as f1’, then you need to type ‘reload(f1)’ rather than ‘reload(function1)’. 2 Printing In Python3, printing can be done using print function. print ( ” Hel lo , world ” ) prints ‘Hello, world’. You can also do print ( ” Hel lo , ” , ” world ” ) which prints exactly the same thing as before. If you want to include some stored values in your text, you can simply type them. x = 10 print ( ”There are ” , x , ” people . ” ) prints ”There are 10 people.”. However, whenever you use ‘,’, you inevitably introduce a space. There are few ways to fix this problem. First, we can use formatted string literals. x = 10 f ’ There are {x} people . ’ f ’ There are {x} people . ’ prints ‘There are 10people.’ ‘There are 10 people.’ You simply need to surround your variables with {}. Note that if you don’t have ‘f’ in front, it will simply type ‘There are {x}people.’ ‘There are {x} people.’ The problem is, the text is always surrounded by quotation marks in this case. Second method is by creating a concatenated string. You can concatenate strings just like you are adding numbers. For example, x = ’ Hel lo , ’ + ’ world ’ y = ’ Hel lo , ’ + ’ world ’ print ( x ) print ( y ) 1 prints Hello, world Hello,world Of course, if you do x = 10 t = ’ There are ’ + x + ’ people . ’ Python will print an error TypeError : must be str , not int since x is not a string yet. Thus, you need to convert x to string first. x = str ( x ) %%changing a number in to a s t r i n g . t1 = ’ There are ’ + x + ’ people . ’ t2 = ’ There are ’ + x + ’ people . ’ print ( t1 ) print ( t2 ) prints There are 10 people. There are 10people. Or lastly, you can combine both methods. print ( f ’ There are {x} people . ’ ) print ( f ’ There are {x} people . ’ ) prints the same thing as above. Exercise. Define a function that takes 3 variables 3 Conditionals Just like any other programming languages, Python also has flow control structures like conditionals and loops. The way it works is quite similar to that of MATLAB but there are few important differences. i f cond i t i on1 : do something %%%execute i f cond i t i on1 i s t rue e l i f cond i t i on2 : do something %%%execute i f cond i t i on2 i s t rue else : do something %%%execute i f a l l prev ious c o n d i t i o n s are f a l s e Like before, you don’t need to have ‘elif’ or ‘else’ parts. The most important thing to note is that indentation matters a lot! For example, i f cond i t i on1 : do something else : do something returns an error message SyntaxError : i n v a l i d syntax Similarly, i f cond i t i on1 : do something else do something 2 returns an error message SyntaxError : expected an indented block 4 Assignment 1. Make a script and define a function of 3 variables, f(x, y, z). 2. If y ≤ 0, print ‘y must be positive.’ 3. Calculate cosx+ log y+ z2 and print The value of cosx+ log y+ zˆ2 is .. Make sure you load all necessary packages and there’s no quotation marks. 4. Upload the python file. 3 Functions Printing Conditionals Assignment