Homework 4

CHE 116: Numerical Methods and Statistics

(2/6/2020)


1. Lists Problems

  1. [2 points] Create a variable called x which is a list containing all even numbers less than 100 using the list(range(...)) syntax.

  2. [1 point] Compute the sum of x without using a for loop

  3. [4 points] Compute the sum of x with a for loop.

  4. [1 point] Print the elements of x reversed using a slice

  5. [2 point] Print the second half of x using the len(x) // 2 syntax

  6. [4 points] Create a new empty list y. Using a for loop and the append keyword, make y contain the square of each element of x. So it should contain: [4, 16, ..., ].


In [1]:
#1.1
x = list(range(2,100,2))
print(x)


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]

In [2]:
#1.2
print(sum(x))


2450

In [3]:
#1.3
s = 0
for xi in x:
    s += xi
print(s)


2450

In [4]:
#1.4
print(x[::-1])


[98, 96, 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2]

In [5]:
#1.5
print(x[len(x)//2:])


[50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98]

In [6]:
#1.6
y = []
for xi in x:
    y.append(xi**2)
print(y)


[4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304, 2500, 2704, 2916, 3136, 3364, 3600, 3844, 4096, 4356, 4624, 4900, 5184, 5476, 5776, 6084, 6400, 6724, 7056, 7396, 7744, 8100, 8464, 8836, 9216, 9604]

2. Array Problem

  1. [2 points] Create a variable called a which is an array containing all even numbers less than 100 using the numpy arange syntax.

  2. [1 point] Compute the sum of a without using a for loop

  3. [1 point] Print the elements of a reversed using a slice

  4. [2 points] Print the minimum, maximum, and mean elements of a using numpy functions.

  5. [1 point] Print the square of each element in a without using a for loop or lists. You should just have one line of numpy code.


In [7]:
#2.1
import numpy as np
a = np.arange(2,100,2)
print(a)


[ 2  4  6  8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48
 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96
 98]

In [8]:
#2.2
print(np.sum(a))


2450

In [9]:
#2.3
print(a[::-1])


[98 96 94 92 90 88 86 84 82 80 78 76 74 72 70 68 66 64 62 60 58 56 54 52
 50 48 46 44 42 40 38 36 34 32 30 28 26 24 22 20 18 16 14 12 10  8  6  4
  2]

In [10]:
#2.4
print(np.min(a), np.max(a), np.mean(a))


2 98 50.0

In [11]:
print(a**2)


[   4   16   36   64  100  144  196  256  324  400  484  576  676  784
  900 1024 1156 1296 1444 1600 1764 1936 2116 2304 2500 2704 2916 3136
 3364 3600 3844 4096 4356 4624 4900 5184 5476 5776 6084 6400 6724 7056
 7396 7744 8100 8464 8836 9216 9604]

3 Plotting

For each problem below, use numpy to create x and y arrays which are plotted. Be sure to label your x-axis, y-axis, put the problem number as the title, use at least 500 points, make your figures be 4x3 inches, and add a legend if you have more than one line being plotted.

  1. [6 points] Plot $y = x^2$ from $-1$ to $1$

  2. [8 points] A hanging rope, wire, or chain follows a catenary curve ($y = a\textrm{cosh}\frac{x}{a} - a$), although many including Galileo mistakenly believed hanging ropes a parabolas. Compare the catenary and parabolic ($y = x^2$) curves over $-1$ to $1$ where $a = 0.63$.

  3. [8 points] Compare the functions $\cos x$ and $\cosh x - 1$ from $-\pi/2$ to $\pi/2$


In [12]:
#3.1

import matplotlib.pyplot as plt
%matplotlib inline

x = np.linspace(-1, 1, 500)
y = x**2

plt.figure(figsize=(4,3))
plt.plot(x,y)
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Problem 3.1')
plt.show()



In [19]:
# 3.2
x = np.linspace(-1, 1, 500)
a = 0.62
y2 = a * np.cosh(x / a) - a

plt.figure(figsize=(4,3))
plt.plot(x,y, label='Parabolic')
plt.plot(x,y2, label='Catenary')
plt.legend()
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Problem 3.2')
plt.show()



In [20]:
#3.3

x = np.linspace(-np.pi/2, np.pi/2, 500)
y1 = np.cos(x)
y2 = np.cosh(x) - 1

plt.figure(figsize=(4,3))
plt.plot(x,y1, label='$\cos x$')
plt.plot(x,y2, label='$\cosh x$')
plt.legend()
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.title('Problem 3.3')
plt.show()


4 Expected Value/Variance

Use this probability distribution:

$$ Q = \{\textrm{red},\textrm{ green}, \textrm{blue}\} $$$$ P(\textrm{red}) = 0.1,\, P(\textrm{green}) = 0.5,\, P(\textrm{blue}),\, = 0.4 $$
  1. [2 points] Create a dictionary called prob where the key is the colors as a string and the values are the probability.

  2. [4 points] Starting with this fragment, show that your probability distribution is normalized.

for key,value in prob.items():
    print(key, value)
  1. [4 points] Let's define a random variable $X$ that is 1 for red, 2 for green, and 0 for blue. Using your for loop from 4.2, use boolean statements to set a variable $x$ to what the value of $X$ should be using the key variable. Print out key, x, which should look like red, 1, green, 2...

  2. [4 points] Compute the expected value of x using the for loop from 4.3

  3. [4 points] Compute the variance by hand, showing the steps in Markdown


In [15]:
#4.1
prob = {'red': 0.1, 'green': 0.5, 'blue': 0.4}

In [16]:
#4.2
psum = 0
for key, value in prob.items():
    psum += value
print(psum)


1.0

In [17]:
#4.3
for key,value in prob.items():
    x = 0
    if key == 'red':
        x = 1
    elif key == 'green':
        x = 2
    print(key, x)


red 1
green 2
blue 0

In [18]:
#4.4
ev = 0
for key,value in prob.items():
    x = 0
    if key == 'red':
        x = 1
    elif key == 'green':
        x = 2
    ev += x * value
print(ev)


1.1

4.5

$$ Var(x) = E[x^2] - E[x]^2 $$$$ E[x] = \sum_Q X(q)P(q) $$$$ E[x] = 1 \times 0.1 + 2 \times 0.5 + 0 \times 0.4 = 1.1 $$$$ E[x] = 1^2 \times 0.1 + 2^2 \times 0.5 + 0^2 \times 0.4 = 2.1 $$$$ Var(x) = 2.1 - 1.1^2 = 0.89 $$