EGR 103/Concept List/F23

From PrattWiki
Revision as of 02:26, 20 November 2023 by DukeEgr93 (talk | contribs)
Jump to navigation Jump to search

Lecture 1 - 8/28 - Course introduction

Lecture 2 - 9/1 - Introduction to programming

  • Seven steps of programming The Seven Steps Poster
  • Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
  • Problem: Consider how to decide if a number is a prime number
    • Some "shortcuts" for specific factors (2, 3, and 5, for example) but need to have a generalized approach
    • See if number is evenly divisible by any integer between 2 and the square root of the number - but how do we ask the computer to do that?
    • We can use output to get the computer to ask for a number and we can use input to allow the computer to receive that number
    • We can use math and the mod operator (%) to see if one number is evenly divisible by another, a loop to go through all possible relevant divisors, and a decision structure to choose what to do if we determine that a number is not prime.
  • Very quick tour of Python with Spyder
    • Console (with history tab), info box (with variable explorer, files, and other tabs), and editing window
    • Pushing "play" button or hitting F5 will save the script, change the working directory, and run the script
    • Quick introduction to variable types: int, float, str
    • Quick introduction to indexing: Python is "0" indexed, meaning if there is a collection of items called x, x[0] will be the "first" item in the collection and x[N-1] where N is the total number of items will be the last item. Also, reverse indexing, where x[-1] is the last item and x[-N] is the first item.

Lecture 3 - 9/4 - Introduction to Python

  • No lecture due to Labor Day
  • See User:DukeEgr93/ld for a summary of work to do instead!

Lecture 4 - 9/8 - Built-in functions, formatted printing

  • Python doesn't know everything to start with; may need to import things
    • import MODULE means using MODULE.function() to run - brings in everything in the module under the module's name
    • import MODULE as NAME means using NAME.function() to run - this is the most common one for us
    • from MODULE import FUNCTION1, FUNCTION2, ... means using FUNCTION1(), FUNCTION2() as function calls - be careful not to override things
    • from MODULE import * means importing every function and constant from a module into their own name - very dangerous!
  • Arrays
    • Must import numpy for arrays
    • import numpy as np will be a very common part of code for EGR 103
    • Organizational unit for storing rectangular arrays of numbers
    • Generally create with np.array(LIST) where depth of nested LIST is dimensionality of array
      • np.array([1, 2, 3]) is a 1-dimensional array with 3 elements
      • np.array([[1, 2, 3], [4, 5, 6]]) is a 2-dimension array with 2 rows and 3 columns
    • Math with arrays works the way you expect
      • ** * / // % + -
        • With arrays, * and / work element by element; *matrix* multiplication is a different character (specifically, @)
  • Creating formatted strings using {} and .format() (format strings, standard format specifiers) -- focus was on using s for string and e or f for numerical types, minimumwidth.precision, and possibly a + in front to force printing + for positive numbers.
    • Using {} by themselves will substitute items in order from the format() function into the string that gets created
    • Putting a number in the {} will tell format which thing to get
    • Format specification comes after a : in the {}; if you do not specify a location index, you still have to put a colon in the {}
      • {:s} means string and {:Xs} where X is an integer means reserve at least that much space for a left-formatted string; {:>s} or {:>Xs} where X is a number will right-justify the string
      • {:f} means floating point (default 6 digits after decimal point) and {:X.Yf} reserves at least X spaces (including + or - and the . if it is there) with Y digits after the decimal point for t right-justified number
      • {:e} means floating point (default 6 digits after decimal point) and {:X.Ye} reserves at least X spaces (including + or - and the . if it is there and the letter e and the + or - after the e and the two or three digit number after that) with Y digits after the decimal point for t right-justified number
    • Aside - Format Specification Mini-Language has all the possibilities; we will cover some but not all of these in later classes
    • You can enter numbers in scientific notation with a number followed by the letter e and then a number or negative number for the power of 10; for example, x = 6.02e23 or e = -1.6e-19
    • float can convert scientific notation as well: float("1e-5")

Lecture 5 - 9/11 - Intro to lists, tuples, and strings; Intro to graphs

  • Lists are set off with [ ] and entries can be any valid type (including other lists!); entries can be of different types from other entries; list items can be changed and mutable items within lists can be changed. Lists can be "grown" by using += with the list or l.append().
  • Tuples are indicated by commas without square brackets (and are usually shown with parentheses - which are required if trying to make a tuple an entry in a tuple or a list); tuple items cannot be changed but mutable items within tuples can be
  • Strings are set off with " " or ' ' and contain characters; string items cannot be changed
  • For lists, tuples, and strings:
    • Using + concatenates the two collections
    • Using * with them creates a collection with the original repeated that many times
    • Using += will create a new item with something appended to the old item; the "something" needs to be the same type (list, tuple, or string); this may seem to break the "can't be changed" rule but really a += b is a = a + b which creates a new a.
  • Trinket

  • To read more:
    • Note! Many of the tutorials below use Python 2 so instead of print(thing) it shows print thing
    • Lists at tutorialspoint
    • Tuples at tutorialspoint
  • Plotting
    • Need to import matplotlib.pyplot as plt
    • Create a figure, cerate a set of axes within the figure, plot using that set of axes
    • Plots can have different colors, line styles, and/or point styles
    • Labels and title are added with the set command
    • See Python:Plotting for more info

Lecture 6 - 9/15 - Intro to functions

  • Defined functions can be multiple lines of code and have multiple outputs - we looked at a single output.
  •  def FNAME(local1, local2, ...):
         CODE
         return THING
    
    • Four different types of input parameters - we only really talked about the first two kinds:
      • Required (listed first)
      • Named with defaults (second)
    • We will cover the other kinds later
      • Additional positional arguments ("*args") (third)
      • Additional keyword arguments ("**kwargs") (last)
    • Function ends when indentation stops or when the function hits a return statement
    • Return returns single item as an item of that type
    • The function can see things in the console but the console can't see things in the function
    • When calling the function, you can put arguments in the order the function expects them to appear or you can give the local names when you call the function. You can do some of both, but the "in order" arguments have to be first; once you name one argument in a function call you *must* name all the rest.
  • Writing test codes
    • You will usually test functions by running a script with the function in it; autograders will generally test code by importing the function from your script.
    • Python has a default variable called __name__ that tells you who is running the show - it will be "__main__" if you run a script from the console and it will be the same as the name of the file if you are importing from that file.
    • Given that, including the line if __name__=="__main__": before test code means the test code will run if you run the script with F5 or the play button but not run if you import the function from the module.

Lecture 7 - 9/18 - Functions continued; Decisions

  • Defined functions can be multiple lines of code and have multiple outputs - now lets talk multiple outputs!
  •  def FNAME(local1, local2, ...):
         CODE
         return THING1, THING 2
    
  • If there are multiple items returned, they are stored and returned in a tuple
    • If there is a left side to the function call, it either needs to be a single variable name or a tuple with as many entries as the number of items returned
  • <= < == >= > != work with many types; just be careful about interpreting
  • not can reverse while and and or can combine logical expressions
  • Basics of decisions using if...elif...else
    • Must have logic after if
    • Can have as many elif with logic after
    • Can have an else without logic at the end
    • Flow is solely dependent on indentation!
    • Branches can contain other trees for follow-up questions

Lecture 8 - 9/22 - Loops

  • Basics of loops using while
    • Must have logic; gets evaluated at start and not again until branch ends
    • Useful when you do not know how many times a loop will run (input validation example)
    • break in a loop can break out early
    • continue in a loop goes back to the top early
  • Basics of loops using for
    • for VAR in ITERABLE
      • VAR will take on each item in ITERABLE one at a time; ITERABLE can be a string, list, tuple, array, or range
        • range(N) creates something similar to [0, 1, 2, 3, 4, ..., N-1]
        • range(M, N) creates something similar to [M, M+1, M+2, ..., N-1]
        • range only creates integers
    • Many ways to keep track of items
      • Loop over indices and access specific item in iterable
      • Loop over iterable and keep a separate counter variable
      • Use enumerate(iterable) to create an iterable made up of tuples where the index is entry 0 and the item is entry 1

Lecture 9 - 9/25 - More Strings and Dictionaries

  • Strings
    • Iterable, so you can use a for loop to go through individual letters
    • for idx, letter in enumerate(the_string): could be handy
    • the_string.split("something") will create a list of strings based on splitting the_string at "something" - usually a space with " "
    • "glue".join(a_list) will take strings that are elements in the list and put them into a single string separated by the glue
    • ord(char) will give the numerical value of that character; chr(num) will give the character at number num
  • Dictionaries
    • Collections whose indices are immutables (integer, float, string, tuple)
    • Built with d={key1:values, key2:value2}
    • Extended with d[newkey]=newvalue
    • Look up values with d[key] or d.get(key) or d.get(key, other); for the latter two, if key is not in the dictionary, the get version will return None or other if other is an option.
    • d.keys() will give the keys, d.value() will give the values, and d.items() will give tuples containing the key and the values - the latter is very useful for making a loop using for idx, val in d.items():

Lecture 10 - 9/29 - Surfaces

  • Various ways to set up 3D space on 2D media; Python has $$x$$ coming towards you and to the right, $$y$$ going away from you and to the right, and $$z$$ going up as positive
  • In order to get a 3D plot, you need to add projection="2d" when you add the subplot
  • If making a space curve, give the $$x$$, $$y$$, and $$z$$ coordinates to the plot command
  • If making a wireframe or a surface, you will likely need to use meshgrid() to create your two independent variables.
  • See Python:Plotting Surfaces

Lecture 11 - 10/2 - Coordinate Systems

  • 2D
    • Cartesian coordinates: use $$x$$ and $$y$$ to indicate location
    • Polar: use distance from origin $$r$$ and angle from positive $$x$$-axis $$\theta$$ to indicate location
    • $$\begin{align*} r&=\sqrt{x^2+y^2} & \theta&=\mbox{atan2}(y, x)\\ x&=r\,\cos(\theta) & y&=r\,\sin(\theta) \end{align*}$$
  • 3D
    • Cartesian coordinates: use $$x$$, $$y$$, and $$z$$ to indicate location
    • Cylindrical coordinates: use $$r$$ and $$\theta$$ to find "shadow" in the $$x-y$$ plane and $$z$$ for distance above/below that plane
    • Spherical coordinates: use distance from the origin $$\rho$$, angle from the positive $$z$$ axis $$\phi$$, and rotation about the $$z$$ axis measured from the positive $$x$$ axis $$\theta$$
    • $$\begin{align*} \begin{array}{cccccccccc}\\ \mbox{ } & x & y & z & r & \theta & z & \rho & \phi & \theta \\ \mbox{From Cartesian:} & x & y & z & \sqrt{x^2+y^2} & \mbox{atan2}(y, x) & z & \sqrt{x^2+y^2+z^2} & \mbox{asin}(\sqrt{x^2+y^2}/\sqrt{x^2+y^2+z^2}) & \mbox{atan2}(y, x)\\ \mbox{From Cylindrical:} & r\,\cos(\theta) & r\,\sin(\theta) & z & r & \theta & z & \sqrt{r^2+z^2} & \mbox{asin}(r/\sqrt{r^2+z^2}) & \theta\\ \mbox{From Spherical:} & \rho\,\sin(\phi)\,\cos(\theta) & \rho\,\sin(\phi)\,\sin(\theta) & \rho\,\cos(\phi) & \rho\,\sin(\phi) & \theta & \rho\,\cos(\phi) & \rho & \phi & \theta \end{array}\end{align*}$$

Lecture 12 - 10/6 - Numerical Representation and Unavoidable Errors

Lecture 13 - 10/9 - Iterative Methods for Maps and Accumulations

Lecture 14 - 10/13 - Logical Masks

Lecture 15 - 10/15 - Monte Carlo Methods

Lecture 16 - 10/23 - Roots

Lecture 17 - 10/27 - More Roots

Lecture 18 - 10/30 - Optimization

Lecture 19 - 11/3 - Complex Number intro; Newton Fractals

Lecture 20 - 11/6 - Basic Linear Algebra

Lecture 21 - 11/10 - Numerical Integration

Lecture 22 - 11/13 - Numerical Differentiation

Lecture 23 - 11/17 - Object-oriented Programmnig