import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
bal = 1000
bal_array = np.zeros(18*12+1)
for i in range(18*12):
n_bal = bal + 0.005*bal + 100
bal_array[i+1]=n_bal
bal = n_bal
fig, ax = plt.subplots()
ax.plot(bal_array)
ax.set_title("College savings over 18 years vs. # months saved")
ax.set_ylabel("Amount Saved ($)")
ax.set_xlabel("Number of Months (#)")
plt.show()
# tell the user how much they saved after 18 years
sav = bal_array[-1] # index out the last value from the array
print(f"After 18 years, you saved ${round(sav,2)}")
After 18 years, you saved $41672.09
# Prototype the function in a Jupyter notebook code cell
import numpy as np
# prototype out the function to approximate e
def eapprox(K):
k_array = np.random.randint(1,K+1,K)
J=0
for i in range(1,K+1):
if not (i in k_array):
J = J + 1
e = K/J
return e
# See how NumPy's np.random.randint() function works
import numpy as np
np.random.randint(1,6,5)
array([5, 3, 3, 1, 1])
# make sure the prototype function can be called in a Jupyter notebook
eapprox(100000)
2.711570270343556
# make sure the myfunc.py file is in the same directory as the running notebook
%ls
Volume in drive C is Windows Volume Serial Number is B899-AB94 Directory of C:\Users\student\Desktop 12/02/2019 11:44 AM <DIR> . 12/02/2019 11:44 AM <DIR> .. 12/02/2019 10:11 AM <DIR> .ipynb_checkpoints 12/02/2019 11:07 AM <DIR> __pycache__ 12/02/2019 09:50 AM 2,502 HW_Problem_Example.ipynb 12/02/2019 11:22 AM 1,457 Kaltura Capture.lnk 05/13/2016 12:33 PM 210 MSDS Online.url 12/02/2019 11:06 AM 249 myfunc.py 08/01/2018 03:14 PM <DIR> Safety Information 12/02/2019 11:44 AM 23,672 Week11_Exam2_Practice_Problems.ipynb 5 File(s) 28,090 bytes 5 Dir(s) 320,424,710,144 bytes free
# Make sure the function can be imported from the myfuncs.py file
from myfunc import eapprox
eapprox(100)
2.380952380952381
# The Finished Program
from math import exp
from myfunc import eapprox
# pick a number for k
k = 5
# call the eapprox function that runs a loop to calcaluate e
approx = eapprox(k)
# use Python's exp() function to calculate e
exact = exp(1)
# print out the approximation of e and the difference between
# the approximation and exp()
error = abs(approx-exact)
print(f"The approximation of e is: {approx} and the error is {round(error,5)}")
The approximation of e is: 5.0 and the error is 2.28172