# Numerical Methods

## Contents |

## Overview

This class is a project-based introduction to computer science using the Python programming language. We will start with a rapid overview of the basic components of programming--variables, expressions and functions-- and debugging. We will then fill out our knowledge with applications.

**References**:

- Text: Think Python by Alan Downey (pdf)
- Python (ver. 2.7): Python Language Reference
- Numerical Python Documentation: NumPy
- VPython: VPython Full Documentation

**Grading:**
Your grade will be based on your work on projects and assignments.

- Daily Assignments: 30%
- Weekly Projects: 40%
- Individual Project: 30%

## Session 1: Thinking About Texts

Spark: Sebastian Wernicke: Lies, damned lies and statistics (about TEDTalks)

Students will do statistical comparisons of their own and published texts to answer questions such as: how has their writing evolved over time; how do different styles of writing evoke different emotional responses?

- In addition to working with files, they will learn lists, iteration, logical operations, user-defined functions (and scoping), and have an introduction to sorting algorithms.
- They will also learn about documenting code.
- References:

### Week 1: Introduction to Coding

- 8/29: Write a program to calculate the average word length in a sentence.
- 8/30: Individual: Write a program that will calculate some statistics from a text.
- E.g. A program that calculates the scrabble score of a word.

### Week 2: Functions and Classes

- Simplify your code by creating functions for things that repeat in your code.
- Make your code a function that can be called by other programs
- As a group, we will make a text analysis Class that combines everyone's functions

#### Assignment: pointWorks

- Make a Class that has methods to perform operations on two points. Specifically:
- The Class should expect two points when it is initiated.
- The Methods should include:
- slope: finding the slope between the two points
- intercept: find the intercept of the line that goes through the two points
- midpoint: find the midpoint between the two points
- distance: find the distance between the two points.

- Write a program that uses your pointWorks class to find the perimeter of a triangle defined by three points.

#### Assignnment: textStats

- You will be given two texts (A and B) with known authors. You will then be given a third text which will be by one of the two authors of the first two texts and you will write a program to identify if it is the author of A or B.
- REQUIRED: You must create and use a Class that calculates statistics for a single text file (name it what you like but I'll call it "textStats" for now).
- This Class should require the name of the file when it is initiated.

- Your program will use instances of this Class to get the statistics from each text, but the program itself will compare the two texts and output its prediction of the author.

- REQUIRED: You must create and use a Class that calculates statistics for a single text file (name it what you like but I'll call it "textStats" for now).

- Assessment:
- 5: Your program meets all of the requirements listed above, particularly:
- There is a clear separation of responsibilities for your textStats Class and the main program that calls it.
- Your program makes its prediction based on the comparison of multiple statistics.
- Your main program is easy to follow because of well named variables and methods.
- All functions and methods are commented to explain what they do and what types of variables they expect to be passed to them and what types of variables they return (You do not need to do line-by-line comments of your code unless you really want to. Just comments for each function and method).

- 4: Your program meets the requirements listed in the instructions:
- There is a clear separation of responsibilities for your textStats Class and the main program that calls it.
- Your program makes its prediction based on only one or two statistical measures (unless you include a good written explanation of why you believe the prediction is good based on only those measures.
- Your method and variable names do not indicate their purpose.
- Your methods and functions are not all commented to express their purpose.

- 3: Your program does not meet all of the requirements listed in the instructions:
- There is not a clear separation of responsibilities for your textStats Class and the main program that calls it.
- Your program gives statistics for the text files but does not give a prediction.
- Your method and variable names do not indicate their purpose.
- Your methods and functions are not all commented to express their purpose.

- 2: Your program does not meet the requirements listed in the instructions:
- There is not a clear separation of responsibilities for your textStats Class and the main program that calls it.
- Your program does not use a textStats-like class.
- Your method and variable names do not indicate their purpose.
- Your methods and functions are not all commented to express their purpose.

- 1: Your program is incomplete.
- It does not produce statistics about the text.
- It has obvious run-time errors.
- Methods and variables are not well named
- Methods and functions are not commented.

- 5: Your program meets all of the requirements listed above, particularly:

### Class and Methods Practice

Q1:

- Write a Class that works with quadratic equations (2nd order polynomials). Initialize it with the coefficients of the polynomial. It should have methods that:
- Takes an x value and returns the f(x) value.
- Returns the x and y values of the critical point of the function.
- Takes an x value and returns the f'(x) value.
- Returns the zeros of the function (if any).
- Draws the graph (using vpython) of the function.

Q2:

- Write a statistics Class.
- It takes a list of data as input: e.g. [2, 5, 84, 21 ...]
- It has methods that calculate the:
- mean
- standard deviation
- mode
- median

### Week 3: Numerical Approaches to Limits

Working with sequences. Write programs to:

- Print out the first 20 integers: [0...19]
- Print out the first 20 even numbers: [0, 2, 4, ...]
- Print out the first 20 odd numbers: [1, 3, 5, ...]
- Print out the first 20 numbers in the sequence: 2i+1
- Print out x and f(x) co-ordinate pairs for the function f(x) = 2x+1 for the all integer values of x between -11 and 11.
- Print out x and f(x) co-ordinate pairs for the function f(x) = x
^{2}+2x+2 for the all integer values of x between -11 and 11. - Print out x and f(x) co-ordinate pairs for the function f(x) = 1/x for the all integer values of x between -11 and 11. (Hint: try-except)
- Challenge: Print out the first 20 Fibonacci numbers: [1, 1, 2, 3, 5, 8, ...]

Sums: Write programs to (start with i=1) Media:Sums.pdf:

- Find the sum of the first 20 integers.
- Find the sum of the first 20 even numbers.
- Find the sum of the first 20 odd numbers.
- Find the sum of the first 20 numbers in the sequence "2i+1" (start with i = 1)
- Find the sum of the first 20 numbers in the sequence "i^2+2i+2" (start with i = 1)
- Find the sum of the first 20 numbers in the sequence "1/i" (start with i = 1)
- Challenge: Find the sum of the first 20 number in the Fibonacci sequence.
- Functions Practice:
- Write a function that sums the first 20 numbers in any sequence passed to it (Pass the sequence as another function)
- Modify your function so it is able to sum the items in any subset of a sequence if the function is given the sequence, the starting item number and the ending item number.

- Answers:
- 1) 210
- 2) 420
- 3) 400
- 4) 440
- 5) 3330
- 6) 3.59773965714
- 7) 17710

Limits:

- Write programs to determine the following limits: Media:Limits.pdf
- Write a program to determine the slope of a function (f(x)) at a given x value.

## Session 2: Modelling data

Students will attempt to model datasets (find the equations that best fit the data) using linear regression methods in spreadsheet programs and then program their own regression solver and build a graphing application.

- In addition to working with datasets, students will learn to work with arrays and create classes.

## Session 3: Motion Driven by Forces and Agents

Students will model force driven motion starting with simple projectile motion and then move creating agents capable of autonomous motion in a physics based physical environment.

- Reference: Advanced Physics

### Analytical Solutions to Differential Equations: Motion

Find the analytical solutions for the following problems and then write a program to output the required table. (Calculus reference: Kinematics & Calculus)

1-dimensional motion

- A ball starts at the origin and moves horizontally at a speed of 0.5 m/s.
- Print out a table of the ball's position (in x) with time (every second) for the first 20 seconds.

- A ball starts at the origin and moves horizontally with an acceleration of 0.2 m/s
^{2}.- Print out a table of the ball's position (in x) with time (every second) for the first 20 seconds.

- A ball starts at the origin and moves horizontally with a jerk of 0.1 m/s
^{3}.- Print out a table of the ball's position (in x) with time (every second) for the first 20 seconds.

- A ball starts at the position (-5, 0) and moves horizontally at a speed of 0.5 m/s.
- Print out a table of the ball's position (in x) with time (every second) for the first 20 seconds.

- A ball starts at the position (0, 10) and moves vertically with an acceleration of -0.2 m/s
^{2}.- Print out a table of the ball's position (in y) with time (every second) for the first 20 seconds.

- A ball starts at the position (0, 5) with an initial, vertical speed of 1 m/s and an acceleration of -0.5 m/s
^{2}.- Print out a table of the ball's position (in y) with time (every second) for the first 20 seconds.

2-dimensional motion

- A ball starts at the origin and moves with a velocity vector of <0.5, 1.0> m/s
- Print out a table of the ball's position with time (every second) for the first 20 seconds.

- A ball starts at the position (-3, -5) with an initial velocity of <2.0, 1.0> m/s and an acceleration of <1.0, -0.5> m/s
^{2}- Print out a table of the ball's position with time (every second) for the first 20 seconds.

- A ball starts at the origin (<0, 0>) with an initial velocity of <10,10> m/s and an acceleration of <0, -9.8> m/s
^{2}- Print out a table of the ball's position with time (every 0.1 seconds) for the first 2 seconds.

Piecewise motion

- A ball starts at the origin and moves horizontally at a speed of 0.5 m/s, after 10 seconds the ball's speed changes to -1.0 m/s for 10 more seconds.
- Print out a table of the ball's position (in x) with time (every second) for the first 20 seconds.

- A ball starts at the origin and:
- for 10 seconds moves horizontally with an acceleration of 1.0 m/s
^{2}, - then for 5 seconds the ball accelerates at -0.25 m/s
^{2}horizontally, - the ball then coasts for 5 seconds
- finally the ball accelerates for 10 seconds vertically at 2 m/s
^{2}. - Print out a table of the ball's position with time (every second) for the first 30 seconds.

- for 10 seconds moves horizontally with an acceleration of 1.0 m/s

### Numerical approximations

References:

Solve the problems in the section using Numerical approximations. Print out a table with time and both numerical and analytical results and then compare the numerical results to the analytical results by calculating the average mean-squared difference: i.e. (Σ(X_{numerical}-X_{analytical})^{2})/n

### Particle Motion

Assignments:

- Motion using vectors:
- Create a simulation of a ball that starts with an initial velocity of <10,10> at the origin <0,0> affected by gravitational acceleration <0,-9.8>. The ball will bounce off the ground (when y = 0) and walls at 20m and -20m in the x direction.

- Make an explosion:
- Create a simulation of
**n**particles that "explode" from the origin with randomly assigned initial velocities.

- Create a simulation of
- Motion due to Force:
- Create a simulation of a cannon ball of mass (
**m**) of 2 kg that is fired from the origin with a force (**F**) of 1000 N over a time (**t**) of 0.1 seconds. - Remember: F = ma

- Create a simulation of a cannon ball of mass (
- Gravitational Motion
- Create a simulation of two particles that move due to the gravitational force between the two.
- F
_{g}= G m_{1}m_{2}/ d^{2}

### Particle Motion 2 (User Input): Potato Cannon

Day 1: George has built and tested a potato cannon. He measured the hang time of the projectile (a potato) (e.g. 5.19 seconds) that is shot--more or less--vertically.

- Write a program to determine the maximum height of the potato. Use the analytical solution (Bonus: find a numerical solution). I.e.:
- Input: hang time
- Output: maximum height, and muzzle velocity of the projectile.

- Write a program that prints out a table with one column for the hang time and another for the maximum height. There will be 4 rows in the table.
- Write a program that will allow the user to type in the hang time and then output the maximum height
- User the raw_input function to get user input from the python shell command line

- Place your function into an infinite loop so the user can enter values as many times as they would like.
- Create a simulation using vpython that shows a projectile moving up and down for the given hang time.

Day 2: George would like to fire his potato cannon at an angle.

- Write a program that calculates the hang time and the distance the potato travels when it hits the ground for a given muzzle velocity and launch angle.
- Inputs: muzzle velocity and launch angle
- Output: hang time and distance the potato travels

- Create a simulation of the potato's flight path using vpython (include a trail so we can see the path of the projectile)
- Adapt your program to show simulations of potato flight paths for 2 different launch angles so we can compare flight paths.
- Adapt your program to simulate flight paths for angles from 10 to 80 degrees in 10 degree increments.

Day 3: Numerical Solution

- Determine the angle a which the cannon will achieve the maximum distance.
- Analytically, and,
- Numerically

- Write a program that will accept the distance to the target and a muzzle velocity and will output the angle of the cannon needed to hit the target.

### Final Exam

## Project Euler

To practice some basic programming techniques, students will spend two days working on problems on Project Euler. Your objective is to see how many of their problems you can get done in this time.

## Session 4: Finite Difference Methods

Students will solve boundary-value differential equation problems using finite difference methods.

- This will also involve writing a Gaussian Elimination Matrix Solver.

## Session 5: Independent Project

Students will pursue their interests in creating their own programming projects.

- These are not restricted to Python so may include designing websites (using client and server-side languages such as Javascript and PHP), or robotics with microcontrollers such as Arduinos.