Week 1 more stuff

Load in packages first

In [3]:
import matplotlib.pyplot as plt
import numpy as np

%matplotlib inline
%config InlineBackend.figure_format='retina'

Lets make a definition

In [4]:
def Compound_interest(t, P, r, n):
    return P*(1+r/n)**(n*t)
In [5]:
Compound_interest(1,1000,0.03,12)
Out[5]:
1030.4159569135068
In [6]:
P = 13000
r=0.067
n=12

X_vals= np.arange(0,100)
In [7]:
plt.plot(X_vals,Compound_interest(X_vals,P,r,n),c='red')
plt.title("Funky Growth rate")
plt.xlabel('Time in Years')
plt.ylabel('Money in Dollars')
plt.show()
In [8]:
for rate in range(3,8):
    r = rate/100
    plt.plot(X_vals,Compound_interest(X_vals,P,r,n),label=r)
plt.title("Funky Growth rate")
plt.xlabel('Time in Years')
plt.ylabel('Money in Dollars')
plt.legend()
plt.show()

Lets make some graphs

In [9]:
X=np.arange(0,6*np.pi)
plt.plot(X,np.sin(X))
plt.show()
In [10]:
X=np.arange(0,6*np.pi)
plt.plot(X,np.sin(X),'x')
plt.show()
In [11]:
X=np.arange(0,6*np.pi,1)
plt.plot(X,np.sin(X),c='r')
plt.show()
In [12]:
X=np.arange(0,6*np.pi,0.01)

plt.plot(X,np.sin(X),c='r')

plt.show()
In [13]:
plt.figure(figsize=(13,5))
X=np.arange(0,6*np.pi,0.01)
plt.plot(X,np.sin(X),c='r')

plt.show()
In [16]:
X=np.arange(0,6*np.pi,0.01)
plt.figure(figsize=(15,5))
plt.subplot(2,1,1)
plt.plot(X,np.sin(X),c='r')
plt.subplot(2,1,2)

plt.plot(X,np.cos(X),c='b')
Out[16]:
[<matplotlib.lines.Line2D at 0x7fec70b2ce10>]
In [17]:
X=np.arange(0,6*np.pi,0.01)
plt.figure(figsize=(13,6))
plt.subplot(2,2,1)
plt.plot(X,np.sin(X),c='r')
plt.subplot(2,2,2)
plt.plot(X,np.sin(X),c='b')
plt.subplot(2,2,3)
plt.plot(X,np.sin(X),c='g')
plt.subplot(2,2,4)
plt.plot(X,np.cos(X),c='y')
Out[17]:
[<matplotlib.lines.Line2D at 0x7fec88ea3410>]
In [19]:
X=np.arange(0,6*np.pi,0.01)
plt.figure(figsize=(13,6))
plt.subplot(2,2,1)
plt.plot(X,np.sin(X),c='r',linestyle='-.')
plt.subplot(2,2,2)
plt.plot(X,np.sin(X),c='aqua',linestyle='--',alpha=0.83)
plt.subplot(2,2,3)
plt.plot(X,np.sin(X),c='g')
plt.grid( color='grey', alpha=0.3, linestyle='--', linewidth=2)
plt.subplot(2,2,4)
plt.plot(X,np.cos(X),c='b',alpha = 0.2)
plt.tick_params(axis='both', direction='out', length=6, width=2, labelcolor='b', colors='r', grid_color='gray', grid_alpha=0.5)
plt.grid()
plt.savefig('Random.png')
In [20]:
print(plt.style.available)
['seaborn-dark', 'seaborn-darkgrid', 'seaborn-ticks', 'fivethirtyeight', 'seaborn-whitegrid', 'classic', '_classic_test', 'fast', 'seaborn-talk', 'seaborn-dark-palette', 'seaborn-bright', 'seaborn-pastel', 'grayscale', 'seaborn-notebook', 'ggplot', 'seaborn-colorblind', 'seaborn-muted', 'seaborn', 'Solarize_Light2', 'seaborn-paper', 'bmh', 'tableau-colorblind10', 'seaborn-white', 'dark_background', 'seaborn-poster', 'seaborn-deep']
In [26]:
plt.style.use('tableau-colorblind10')
plt.figure(figsize=(13,5))
X=np.arange(0,6*np.pi,0.01)
plt.plot(X,np.sin(X),c='r')

plt.show()
In [29]:
plt.style.use('default')

Lists and things

In [30]:
Xb = [2,6,4,3,8,9]
In [31]:
Xb
Out[31]:
[2, 6, 4, 3, 8, 9]
In [32]:
len(Xb)
Out[32]:
6
In [34]:
Xb.pop?
Signature: Xb.pop(index=-1, /)
Docstring:
Remove and return item at index (default last).

Raises IndexError if list is empty or index is out of range.
Type:      builtin_function_or_method
In [33]:
Xb.pop()
Out[33]:
9
In [35]:
len(Xb)
Out[35]:
5
In [36]:
Xb.pop(2)
Out[36]:
4
In [37]:
len(Xb)
Out[37]:
4
In [38]:
Xb
Out[38]:
[2, 6, 3, 8]
In [39]:
Xb.sort()
In [40]:
Xb
Out[40]:
[2, 3, 6, 8]
In [41]:
Xb.index(3)
Out[41]:
1
In [42]:
x,y = 2,3
In [43]:
x/y
Out[43]:
0.6666666666666666
In [44]:
print(x/y)
0.6666666666666666
In [45]:
print(round(x/y,2))
0.67
In [47]:
print("{:.4f}".format(x/y))
0.6667

type()

In [48]:
type(round(x/y,2))
Out[48]:
float
In [49]:
type("{:.4f}".format(x/y))
Out[49]:
str

Random Numpy

In [50]:
np.random.random()
Out[50]:
0.21000225147838858
In [52]:
np.random.random?
Docstring:
random(size=None)

Return random floats in the half-open interval [0.0, 1.0). Alias for
`random_sample` to ease forward-porting to the new random API.
Type:      builtin_function_or_method
In [55]:
np.random.normal()
Out[55]:
-1.94043459220759
In [57]:
np.random.normal?

Lets make some Random walks and see where the computer will lead us!

In [58]:
def Move(x,y):
    rand = np.random.random()
    if rand<=0.25:
        x = x+rand
    elif rand<=0.5:
        y = y + rand-0.25
    elif rand <=0.75:
        x = x - (rand - 0.5)
    else:
        y = y - (rand -0.75)
        
    return x,y
In [70]:
Move(401,23)
Out[70]:
(400.85463758108324, 23)
In [73]:
plt.xlim(-5,5)
plt.ylim(-5,5)
x,y=0,0
count = 0
plt.plot(x,y,'o',c='b')
while x**2<=25 and y**2<=25 and count<=1000:
    
    plt.plot(x,y,'.',c='r',alpha = 0.1)
    x,y = Move(x,y)
    count =count + 1
plt.show()    
print(count)
1001
In [74]:
for L in range(1,10):
    plt.xlim(-5,5)
    plt.ylim(-5,5)
    x,y=0,0
    count = 0
    plt.plot(x,y,'o',c='b')
    while x**2<=25 and y**2<=25 and count<=5000:
    
        plt.plot(x,y,'.',c='r',alpha = 0.1)
        x,y = Move(x,y)
        count =count + 1
    plt.show()    
    print(count)
762
1214
765
4700
379
3056
946
882
1021

Model $\pi$

randomize throwing ink on a painting, then

$$\frac{\text{green area}}{\text{green + red}} = \frac{\pi}{4} $$

  • make a circle
  • create a random paint throwing thing
  • color the paint after it lands depending on where it lands
  • count the green and red and then calculate $\pi$
  • make it faster, .......profit

First circle

In [75]:
x=np.arange(-1,1,0.00001)
In [76]:
top_half = (1-x**2)**(0.5)
bottom_half = -(1-x**2)**(0.5)
In [78]:
plt.figure(figsize=(7,7))
plt.plot(x,top_half,c='b')
plt.plot(x,bottom_half,c='b')
Out[78]:
[<matplotlib.lines.Line2D at 0x7fec686cac90>]

Another way is to use trig!!

In [80]:
plt.figure(figsize=(7,7))
t=np.arange(-2*np.pi,2*np.pi,0.0001)
plt.plot(np.cos(t), np.sin(t), linewidth=1)
Out[80]:
[<matplotlib.lines.Line2D at 0x7fec72196ad0>]
In [81]:
Inside = 0
Outside =0
In [82]:
plt.figure(figsize=(10,10))
t=np.arange(-2*np.pi,2*np.pi,0.0001)
plt.plot(np.cos(t), np.sin(t), linewidth=1)
Out[82]:
[<matplotlib.lines.Line2D at 0x7fec686ad250>]
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [89]:
%%time
Inside = 0
Outside =0
plt.figure(figsize=(7,7))
t=np.arange(-2*np.pi,2*np.pi,0.0001)
plt.plot(np.cos(t), np.sin(t), linewidth=1)
for count in range(0,5000):
    x = np.random.random()*np.random.choice([-1,1])
    y = np.random.random()*np.random.choice([-1,1])
    if x**2 +y**2<1:
        color = 'g'
        Inside +=1
    else:
        color = 'r'
        Outside +=1
    plt.plot(x,y,'o',c=color, alpha =0.1)

print("{:.8f}".format(4*Inside/(Outside+Inside)))
3.15440000
CPU times: user 12 s, sys: 24.5 ms, total: 12 s
Wall time: 12 s
In [ ]:
#plt.savefig('Name_of_Graph.png')
In [90]:
%%time
Inside = 0
Outside =0
Num_of_Points=5000

plt.figure(figsize=(7,7))
t=np.arange(-2*np.pi,2*np.pi,0.0001)
plt.plot(np.cos(t), np.sin(t), linewidth=1)

x = np.random.random_sample(Num_of_Points)*np.random.choice([-1,1],size=Num_of_Points)
y = np.random.random_sample(Num_of_Points)*np.random.choice([-1,1],size=Num_of_Points)

for count in range(0,Num_of_Points):
    if x[count]**2 +y[count]**2<1:
        color = 'g'
        Inside +=1
    else:
        color = 'r'
        Outside +=1
    plt.plot(x[count],y[count],'o',c=color, alpha =0.2)

print("{:.8f}".format(4*Inside/(Outside+Inside)))
3.11360000
CPU times: user 13.1 s, sys: 27.6 ms, total: 13.1 s
Wall time: 13.1 s

Heavy lifters: Pandas

In [91]:
import pandas as pd
In [96]:
%%time
Inside = 0
Outside =0
Num_of_Points=5000000

plt.figure(figsize=(7,7))
t=np.arange(-2*np.pi,2*np.pi,0.0001)
plt.plot(np.cos(t), np.sin(t), linewidth=1)

x = np.random.random_sample(Num_of_Points)*np.random.choice([-1,1],size=Num_of_Points)
y = np.random.random_sample(Num_of_Points)*np.random.choice([-1,1],size=Num_of_Points)

z=x**2+y**2-1
df = pd.DataFrame({'x':x,'y':y,'z':z})
df_in=df[df.z<0]
df_out=df[df.z>=0]

plt.plot(df_in.x,df_in.y,'o',c='g',alpha=0.01)
plt.plot(df_out.x,df_out.y,'o',c='r',alpha=0.01)


print("{:.8f}".format(4*len(df_in)/(len(df_out)+len(df_in))))
3.13998880
CPU times: user 492 ms, sys: 138 ms, total: 630 ms
Wall time: 631 ms
In [ ]: