Difference between revisions of "EGR 103/Concept List/S22"

From PrattWiki
Jump to navigation Jump to search
(Created page with "== Lecture 1 - 1/7 - Course Introduction == * Main class page: [http://classes.pratt.duke.edu/EGR103S22/ EGR 103L]. * See information on PDF of slide show on Sakai in Resource...")
 
Line 5: Line 5:
 
* Pundit page: [[EGR 103]]; reference lists
 
* Pundit page: [[EGR 103]]; reference lists
 
* Ed page: [https://edstem.org/us/courses/16734/discussion/ 103L page]; message board for questions
 
* Ed page: [https://edstem.org/us/courses/16734/discussion/ 103L page]; message board for questions
 +
 +
 +
== Lecture 2 - 1/10- Programs and Programming ==
 +
* Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
 +
* Seven steps of programming [https://adhilton.pratt.duke.edu/sites/adhilton.pratt.duke.edu/files/u37/iticse-7steps.pdf The Seven Steps Poster]
 +
** Watch video on [https://www.coursera.org/lecture/duke-programming-web/developing-an-algorithm-nopgq Developing an Algorithm]
 +
** Watch video on [https://www.coursera.org/lecture/duke-programming-web/a-seven-step-approach-to-solving-programming-problems-AEy5M A Seven Step Approach to Solving Programming Problems]
 +
* Consider how to decide if a number is a prime number - code is available in the Box drive for the class under Lectures / Lec 03
 +
* To play with Python:
 +
** Install it on your machine or a public machine: [https://www.anaconda.com/download/ Download]
 +
* Quick tour of Python
 +
** Editing window, variable explorer, and console
 +
** Main numerical types: whole numbers (int) and numbers with decimals (float)
 +
** + - * // (rounded division) and % (remainder / modula) produce in if both sides are an int, float if either or both are floats
 +
** / (regular division) and // (rounded division) produces float with ints or floats
 +
** ** to do powers
 +
 +
 +
== Lecture 3 - 1/14 - Indexing and "Number" Types ==
 +
* Demonstrated how cells work in Spyder editor
 +
* Slices allow us to extract information from a collection or change information in mutable collections
 +
** a[0] is the element in a at the start
 +
** a[3] is the element in a three away from the start
 +
** a[-1] is the last element of a
 +
** a[-2] is the second-to-last element of a
 +
** a[:] is all the elements in a because what is really happening is:
 +
*** a[start:until] where start is the first index and until is just *past* the last index;
 +
*** a[3:7] will return a[3] through a[6] in a 4-element array
 +
*** a[start:until:increment] will skip indices by increment instead of 1
 +
*** To go backwards, a[start:until:-increment] will start at an index and then go backwards until getting at or just past until.
 +
** For 2-D arrays, you can index items with either separate row and column indices or indices separated by commas:
 +
*** a[2][3] is the same as a[2, 3]
 +
*** Only works for arrays!
 +
* Getting values from a user:
 +
** <code>VAR = input("prompt: ")</code> will ask the user for a value and stores whatever they type as a string
 +
** <code>NUM = int(VAR)</code> will convert the item in VAR to an integer if it looks like an integer; error otherwise
 +
** <code>NUM = float(VAR)</code> will convert the item in VAR to a float if it looks like a float; error otherwise
 +
* Finished prime number checker - code is available in the Box drive for the class under Lectures / Lec 03
 +
** Looked at for loops for running code multiple times
 +
** Looked at if...else trees for making decisions
 +
** Created a variable to track whether we thought the number was prime
 +
* Python doesn't know everything to start with; may need to import things
 +
** <code>import MODULE</code> means using <code>MODULE.function()</code> to run
 +
** <code>import MODULE as NAME</code> means using <code>NAME.function()</code> to run
 +
** <code>from MODULE import FUNCTION</code> means using <code>FUNCTION()</code> to run
 +
** <code>from MODULE import *</code> means bringing in everything from the module under their own names - dangerous!
 +
* Python is a "typed" language - variables have types.  We will use several types:
 +
** Focus of the day: int, float, and array
 +
** Focus a little later: string, list, tuple
 +
** Focus later: dictionary, set
 +
** Focus way later: map, filter, zip
 +
* int: integers; Python 3 can store these perfectly
 +
* float: floating point numbers - "numbers with decimal points" - Python sometimes has problems storing floating point items exactly
 +
* array
 +
** Requires numpy, usually with <code>import numpy as np</code>
 +
** 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 "Number" types works the way you expect
 +
** ** * / // % + -
 +
** With arrays, * and / work element by element; *matrix* multiplication is a different character (specifically, @)
 +
* Relational operators can compare "Number" Types and work the way you expect with True or False as an answer
 +
** < <= == >= > !=
 +
** With arrays, either same size or one is a single value; result will be an array of True and False the same size as the array
 +
 +
== Lecture 4 - 1/21 - Other Types, Formatted Printing ==
 +
* 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.
 +
* 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 makes 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 <code>a += b</code> is <code>a = a + b</code> which creates a new <code>a</code>.
 +
* Creating formatted strings using {} and .format() ([https://www.python.org/dev/peps/pep-3101/#format-strings format strings], [https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers 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 <code>format()</code> function into the string that gets created
 +
** Putting a number in the {} will tell <code>format</code> 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
 +
** {: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 - [https://docs.python.org/3/library/string.html#format-specification-mini-language 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 3 and then a number or negative number for the power of 10; for example, <code>x = 6.02e23</code> or <code>e = -1.6e-19</code>
 +
** float can convert scientific notation as well:
 +
float("1e-5")
 +
 +
* Characters in strings have "numerical" values based on the ASCII table ([https://www.asciitable.com/ https://www.asciitable.com/])
 +
** Numbers are earlier than lower case letters; lower case letters are earlier than upper case letters
 +
** Strings are sorted character by character; if one string is shorter than another, it is considered less
 +
*** "Hello" < "Hi" since the "e" comes before the "i"
 +
*** "Zebra" < "apple" since the upper case "Z" is before the lower case "a"
 +
*** "go" < "gone" since the first two characters match and then the word is done
 +
* To get the numerical value of a single character, use <code>ord("A")</code> or replace the A with the character you want
 +
* To get the character a number represents, use <code>chr(NUM)</code>
 +
* To apply either ord or chr to multiple items, use a <code>map</code>; to see the results, make a <code>list</code> out of the map
 +
* Trinket
 +
<html>
 +
<iframe src="https://trinket.io/embed/python3/b1113c2184" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>
 +
</html>
 +
* To read more:
 +
** Note!  Many of the tutorials below use Python 2 so instead of <code>print(thing)</code> it shows <code>print thing</code>
 +
** [https://www.tutorialspoint.com/python/python_lists.htm Lists] at tutorialspoint
 +
** [https://www.tutorialspoint.com/python/python_tuples.htm Tuples] at tutorialspoint
 +
 +
== Lecture 5 - 1/17 - Functions ==
 +
* Defined functions can be multiple lines of code and have multiple outputs.
 +
*<syntaxhighlight lang=python>
 +
def FNAME(local1, local2, ...):
 +
    CODE
 +
    return THING1, THING2, ...</syntaxhighlight>
 +
** Four different types of input parameters - we mainly talked about the first two kinds:
 +
*** '''Required (listed first)'''
 +
*** Named with defaults (second)
 +
** We will cover the other kinds in more detail later
 +
*** Additional positional arguments ("*args") (third)
 +
**** Function will create a tuple containing these items in order
 +
*** Additional keyword arguments ("**kwargs") (last)
 +
**** Function will create a dictionary of keyword and value pairs
 +
** Function ends when indentation stops or when the function hits a return statement
 +
** Return returns single item as an item of that type; 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
 +
 +
== Lecture 6 - 1/24 - Relational Operators, Decisions, and Loops ==
 +
* <= < == >= > != work with many types; just be careful about interpreting
 +
* <code>not</code> can reverse while <code>and</code> and <code>or</code> 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
 +
* Movie ratings.
 +
* Basics of while loops and for loops.
 +
* The Price Is Right game!
 +
 +
== Lecture 7 - 1/28 - More Loops and Logical Masks ==
 +
* Using a list to keep track of counts
 +
* Using the <code>enumerate</code> type to provide a collection of indices and values to a loop
 +
* Basics of [[Python:Logical Masks]]
 +
 +
== Lecture 8 - 1/31 - Dictionaries ==
 +
* Dictionaries are collections of key : value pairs set off with { }; keys can be any immutable type (int, float, string, tuple) and must be unique; values can be any type and do not need to be unique
 +
** [https://www.tutorialspoint.com/python/python_dictionary.htm Dictionary] at tutorialspoint
 +
* Storing values in a dictionary
 +
* Bar chart demo
 +
* Translation demo with Morse code and NATO phonetic alphabet
 +
 +
== Lecture 9 - 2/4 - Iterative Methods ==
 +
* Taylor series fundamentals
 +
* Maclaurin series approximation for exponential uses Chapra 4.2 to compute terms in an infinite sum.
 +
<center><math>
 +
y=e^x=\sum_{n=0}^{\infty}\frac{x^n}{n!}
 +
</math>
 +
</center>
 +
:so
 +
<center><math>
 +
\begin{align}
 +
y_{init}&=1\\
 +
y_{new}&=y_{old}+\frac{x^n}{n!}
 +
\end{align}
 +
</math>
 +
</center>
 +
* Newton Method for finding square roots uses Chapra 4.2 to iteratively solve using a mathematical map.  To find <math>y</math> where <math>y=\sqrt{x}</math>: <center><math>
 +
\begin{align}
 +
y_{init}&=1\\
 +
y_{new}&=\frac{y_{old}+\frac{x}{y_{old}}}{2}
 +
\end{align}
 +
</math>
 +
* See Python version of Fig. 4.2 and modified version of 4.2 in the Resources section of Sakai page under Chapra Pythonified
 +
 +
== Lecture 10 - 2/7 - Binary ==
 +
* Different number systems convey information in different ways.
 +
** Roman Numerals
 +
** Chinese Numbers
 +
** Binary Numbers
 +
*** We went through how to convert between decimal and binary
 +
* Floats (specifically double precision floats) are stored with a sign bit, 52 fractional bits, and 11 exponent bits.  The exponent bits form a code:
 +
** 0 (or 00000000000): the number is either 0 or a denormal
 +
** 2047 (or 11111111111): the number is either infinite or not-a-number
 +
** Others: the power of 2 for scientific notation is 2**(code-1023)
 +
*** The largest number is thus just *under* 2**1024 (ends up being (2-2**-52)**1024<math>\approx 1.798\times 10^{308}</math>.
 +
*** The smallest normal number (full precision) is 2**(-1022)<math>\approx 2.225\times 10^{-308}</math>.
 +
*** The smallest denormal number (only one significant binary digit) is 2**(-1022)/2**53 or 5e-324.
 +
** When adding or subtracting, Python can only operate on the common significant digits - meaning the smaller number will lose precision.
 +
** (1+1e-16)-1=0 and (1+1e-15)-1=1.1102230246251565e-15
 +
** Avoid intermediate calculations that cause problems: if x=1.7e308,
 +
*** (x+x)/x is inf
 +
*** x/x + x/x is 2.0
 +
** $$e^x=\lim_{n\rightarrow \infty}\left(1+\frac{x}{n}\right)^n$$
 +
<div class="mw-collapsible mw-collapsed">
 +
<source lang=python>
 +
# Exponential Demo
 +
</source>
 +
<div class="mw-collapsible-content">
 +
<syntaxhighlightlang=python>
 +
import numpy as np
 +
import matplotlib.pyplot as plt
 +
 +
def exp_calc(x, n):
 +
    return (1 + x/n)**n
 +
 +
if __name__ == "__main__":
 +
    n = np.logspace(0, 17, 1000)
 +
    y = exp_calc(1, n)
 +
    fig, ax = plt.subplots(num=1, clear=True)
 +
    ax.semilogx(n, y)
 +
    fig.savefig('ExpDemoPlot1.png')
 +
   
 +
    # Focus on right part
 +
    n = np.logspace(13, 16, 1000)
 +
    y = exp_calc(1, n)
 +
    fig, ax = plt.subplots(num=2, clear=True)
 +
    ax.semilogx(n, y)
 +
    fig.savefig('ExpDemoPlot2.png')
 +
</syntaxhighlight>
 +
</div>
 +
</div>
 +
<gallery>
 +
File:ExpDemoPlot1.png|estimates for calculating $$e$$ with $$n$$ between 1 and $$1*10^{17}$$
 +
File:ExpDemoPlot2.png|$$n$$ between $$10^{13}$$ and $$10^{16}$$ showing region when roundoff causes problems
 +
</gallery>
 +
 +
* Want to see Amharic?
 +
list(map(chr, range(4608, 4992)))
 +
* Want to see the Greek alphabet?
 +
<syntaxhighlight lang=python>
 +
for k in range(913,913+25):
 +
    print(chr(k), chr(k+32))
 +
</syntaxhighlight>

Revision as of 21:26, 7 February 2022

Lecture 1 - 1/7 - Course Introduction

  • Main class page: EGR 103L.
  • See information on PDF of slide show on Sakai in Resources section
  • Sakai page: Sakai 103L page; grades, surveys and tests, some assignment submissions
  • Pundit page: EGR 103; reference lists
  • Ed page: 103L page; message board for questions


Lecture 2 - 1/10- Programs and Programming

  • Almost all languages have input, output, math, conditional execution (decisions), and repetition (loops)
  • Seven steps of programming The Seven Steps Poster
  • Consider how to decide if a number is a prime number - code is available in the Box drive for the class under Lectures / Lec 03
  • To play with Python:
    • Install it on your machine or a public machine: Download
  • Quick tour of Python
    • Editing window, variable explorer, and console
    • Main numerical types: whole numbers (int) and numbers with decimals (float)
    • + - * // (rounded division) and % (remainder / modula) produce in if both sides are an int, float if either or both are floats
    • / (regular division) and // (rounded division) produces float with ints or floats
    • ** to do powers


Lecture 3 - 1/14 - Indexing and "Number" Types

  • Demonstrated how cells work in Spyder editor
  • Slices allow us to extract information from a collection or change information in mutable collections
    • a[0] is the element in a at the start
    • a[3] is the element in a three away from the start
    • a[-1] is the last element of a
    • a[-2] is the second-to-last element of a
    • a[:] is all the elements in a because what is really happening is:
      • a[start:until] where start is the first index and until is just *past* the last index;
      • a[3:7] will return a[3] through a[6] in a 4-element array
      • a[start:until:increment] will skip indices by increment instead of 1
      • To go backwards, a[start:until:-increment] will start at an index and then go backwards until getting at or just past until.
    • For 2-D arrays, you can index items with either separate row and column indices or indices separated by commas:
      • a[2][3] is the same as a[2, 3]
      • Only works for arrays!
  • Getting values from a user:
    • VAR = input("prompt: ") will ask the user for a value and stores whatever they type as a string
    • NUM = int(VAR) will convert the item in VAR to an integer if it looks like an integer; error otherwise
    • NUM = float(VAR) will convert the item in VAR to a float if it looks like a float; error otherwise
  • Finished prime number checker - code is available in the Box drive for the class under Lectures / Lec 03
    • Looked at for loops for running code multiple times
    • Looked at if...else trees for making decisions
    • Created a variable to track whether we thought the number was prime
  • Python doesn't know everything to start with; may need to import things
    • import MODULE means using MODULE.function() to run
    • import MODULE as NAME means using NAME.function() to run
    • from MODULE import FUNCTION means using FUNCTION() to run
    • from MODULE import * means bringing in everything from the module under their own names - dangerous!
  • Python is a "typed" language - variables have types. We will use several types:
    • Focus of the day: int, float, and array
    • Focus a little later: string, list, tuple
    • Focus later: dictionary, set
    • Focus way later: map, filter, zip
  • int: integers; Python 3 can store these perfectly
  • float: floating point numbers - "numbers with decimal points" - Python sometimes has problems storing floating point items exactly
  • array
    • Requires numpy, usually with import numpy as np
    • 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 "Number" types works the way you expect
    • ** * / // % + -
    • With arrays, * and / work element by element; *matrix* multiplication is a different character (specifically, @)
  • Relational operators can compare "Number" Types and work the way you expect with True or False as an answer
    • < <= == >= > !=
    • With arrays, either same size or one is a single value; result will be an array of True and False the same size as the array

Lecture 4 - 1/21 - Other Types, Formatted Printing

  • 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.
  • 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 makes 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.
  • 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
    • {: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 3 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")
  • Characters in strings have "numerical" values based on the ASCII table (https://www.asciitable.com/)
    • Numbers are earlier than lower case letters; lower case letters are earlier than upper case letters
    • Strings are sorted character by character; if one string is shorter than another, it is considered less
      • "Hello" < "Hi" since the "e" comes before the "i"
      • "Zebra" < "apple" since the upper case "Z" is before the lower case "a"
      • "go" < "gone" since the first two characters match and then the word is done
  • To get the numerical value of a single character, use ord("A") or replace the A with the character you want
  • To get the character a number represents, use chr(NUM)
  • To apply either ord or chr to multiple items, use a map; to see the results, make a list out of the map
  • 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

Lecture 5 - 1/17 - Functions

  • Defined functions can be multiple lines of code and have multiple outputs.
  •  def FNAME(local1, local2, ...):
         CODE
         return THING1, THING2, ...
    
    • Four different types of input parameters - we mainly talked about the first two kinds:
      • Required (listed first)
      • Named with defaults (second)
    • We will cover the other kinds in more detail later
      • Additional positional arguments ("*args") (third)
        • Function will create a tuple containing these items in order
      • Additional keyword arguments ("**kwargs") (last)
        • Function will create a dictionary of keyword and value pairs
    • Function ends when indentation stops or when the function hits a return statement
    • Return returns single item as an item of that type; 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

Lecture 6 - 1/24 - Relational Operators, Decisions, and Loops

  • <= < == >= > != 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
  • Movie ratings.
  • Basics of while loops and for loops.
  • The Price Is Right game!

Lecture 7 - 1/28 - More Loops and Logical Masks

  • Using a list to keep track of counts
  • Using the enumerate type to provide a collection of indices and values to a loop
  • Basics of Python:Logical Masks

Lecture 8 - 1/31 - Dictionaries

  • Dictionaries are collections of key : value pairs set off with { }; keys can be any immutable type (int, float, string, tuple) and must be unique; values can be any type and do not need to be unique
  • Storing values in a dictionary
  • Bar chart demo
  • Translation demo with Morse code and NATO phonetic alphabet

Lecture 9 - 2/4 - Iterative Methods

  • Taylor series fundamentals
  • Maclaurin series approximation for exponential uses Chapra 4.2 to compute terms in an infinite sum.
\( y=e^x=\sum_{n=0}^{\infty}\frac{x^n}{n!} \)
so
\( \begin{align} y_{init}&=1\\ y_{new}&=y_{old}+\frac{x^n}{n!} \end{align} \)
  • Newton Method for finding square roots uses Chapra 4.2 to iteratively solve using a mathematical map. To find \(y\) where \(y=\sqrt{x}\):
    \( \begin{align} y_{init}&=1\\ y_{new}&=\frac{y_{old}+\frac{x}{y_{old}}}{2} \end{align} \)
  • See Python version of Fig. 4.2 and modified version of 4.2 in the Resources section of Sakai page under Chapra Pythonified

Lecture 10 - 2/7 - Binary

  • Different number systems convey information in different ways.
    • Roman Numerals
    • Chinese Numbers
    • Binary Numbers
      • We went through how to convert between decimal and binary
  • Floats (specifically double precision floats) are stored with a sign bit, 52 fractional bits, and 11 exponent bits. The exponent bits form a code:
    • 0 (or 00000000000): the number is either 0 or a denormal
    • 2047 (or 11111111111): the number is either infinite or not-a-number
    • Others: the power of 2 for scientific notation is 2**(code-1023)
      • The largest number is thus just *under* 2**1024 (ends up being (2-2**-52)**1024\(\approx 1.798\times 10^{308}\).
      • The smallest normal number (full precision) is 2**(-1022)\(\approx 2.225\times 10^{-308}\).
      • The smallest denormal number (only one significant binary digit) is 2**(-1022)/2**53 or 5e-324.
    • When adding or subtracting, Python can only operate on the common significant digits - meaning the smaller number will lose precision.
    • (1+1e-16)-1=0 and (1+1e-15)-1=1.1102230246251565e-15
    • Avoid intermediate calculations that cause problems: if x=1.7e308,
      • (x+x)/x is inf
      • x/x + x/x is 2.0
    • $$e^x=\lim_{n\rightarrow \infty}\left(1+\frac{x}{n}\right)^n$$
# Exponential Demo

<syntaxhighlightlang=python> import numpy as np import matplotlib.pyplot as plt

def exp_calc(x, n):

   return (1 + x/n)**n

if __name__ == "__main__":

   n = np.logspace(0, 17, 1000)
   y = exp_calc(1, n)
   fig, ax = plt.subplots(num=1, clear=True)
   ax.semilogx(n, y)
   fig.savefig('ExpDemoPlot1.png')
   
   # Focus on right part
   n = np.logspace(13, 16, 1000)
   y = exp_calc(1, n)
   fig, ax = plt.subplots(num=2, clear=True)
   ax.semilogx(n, y)
   fig.savefig('ExpDemoPlot2.png')

</syntaxhighlight>

  • Want to see Amharic?
list(map(chr, range(4608, 4992)))
  • Want to see the Greek alphabet?
for k in range(913,913+25):
    print(chr(k), chr(k+32))