Day 1 Homework
Contents
3. Day 1 Homework#
3.1. Initial Instructions:#
Open a new Google Colab notebook and click on “New Notebook” in the corner.
Here’s the actual homework!
3.2. Exercise 1: Create a Simple Calculator#
For this first exercise you will be generating a simple calculator. Generate a code that can take a string of input such as ‘Add 1 + 2’ together and accurately carry out the operation and report the result. The calculator should be able to handle addition, subtraction, multiplication and division
3.3. Exercise 2: Approximate pi with random numbers#
\(\pi\) is among the most famous of irrational numbers, written approximately as 3.14159. An enormous amount of resources, both human and machine, have exhausted countless hours analyzing \(\pi\)’s decimal contributions, and roughly 100 trillion digits of \(\pi\) are known today. [http://www.numberworld.org/y-cruncher/]
A far less ambitious approximation can be achieved with simple Monte Carlo methods, utilizing random numbers and statistics to converge an estimate for \(\pi\).
Imagine a circle of diameter D inscribed within a square of edge length D. Place the origin of a 2D graph at the circle’s center. The key to approximating \(\pi\) is generating coordinate pairs of random numbers, which correspond to (x,y) positions inside of the square, and counting how many land inside the circle. With a statistically large random sample of coordinate pairs, the ratio of points landing inside the circle to total number of points approximates the ratio of the circle’s area to the square’s area. This is known as the stone throwing problem and is mathmatically formulated as:
\(\frac{A_{circle}}{A_{square}}=\frac{N_{circle}}{N_{square}}\)
where \(A\) represents the shape area and \(N\) represents the number of points to land inside of each shape. Note that all generated points should land within the square, such that \(N_{total}=N_{square}\). Using a little geometry, \(A_{circle}=\pi (\frac{D}{2})^2\) and \(A_{square}=D^2\), the final relation for \(\pi\) is given as:
\(\pi\approx4\frac{N_{circle}}{N_{square}}\)
3.4. Instructions#
Generate a set of N random x,y pairs within a square (2*N random numbers makes N pairs of random numbers)
Count the x,y pairs lying inside of an inscribed circle (is \(x^2+y^2 < (\frac{D}{2})^2\) ?)
Compute an approximation of \(\pi\)