In [1]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import StaticInteract, RangeWidget, RadioWidget
In [4]:
h = 0.1

def fn(k,m,y):
    return -k*y/m

def euler_step(k,m,y,dy):
    F1 = dy
    f1 = fn(k,m,y)
    return [f1*h, F1*h] # [dy, y] update

def main(k,m):
    y = 0
    dy = 1
    i = 0
    ylist = []
    while i<100:
        array = euler_step(k,m,y,dy)
        dy += array[0]
        y += array[1]
        #print y,dy
        ylist.append(y)
        i +=1
    return ylist

def plot(k,m):
    fig, ax = plt.subplots(figsize=(4, 3),
                           subplot_kw={'axisbg':'#EEEEEE',
                                       'axisbelow':True})
    ax.grid(color='w', linewidth=2, linestyle='solid')
    alist = main(k,m)
    ax.plot(alist, lw=5, alpha=0.4, label = m/k)
    ax.legend(loc='upper right')
    #ax.set_xlim(0,2*np.pi)
    #ax.set_ylim(-1, 1)
    return fig
In [5]:
StaticInteract(plot, k=RangeWidget(1., 5., 1.), m=RangeWidget(1., 3., 1.))
Out[5]:
k:
m:

testing

In [27]:
plt.hold(True)
m=1
for k in range(1,4):
    alist = main()
    plt.plot(alist)
In [16]:
def fn(k,m,y):
    return -k*y/m

def euler_step(k,m,y,dy):
    F1 = dy
    f1 = fn(k,m,y)
    return [f1*h, F1*h] # [dy, y] update

i = 0
y = 0
dy = 1
h = 0.1
k = m = 1
ylist = []
while i<100:
    array = euler_step(k,m,y,dy)
    dy += array[0]
    y += array[1]
    #print y,dy
    ylist.append(y)
    i +=1
In [17]:
plt.plot(ylist)
Out[17]:
[<matplotlib.lines.Line2D at 0xb0ff0f4c>]
In []:
 
In [14]:
def fn(k,m,y):
    return -k*y/m

def rk2_step(k,m,y,dy):
    F1 = dy
    f1 = fn(k,m,y)
    F2 = dy +f1*h
    f2 = fn(k,m,y+F1*h)
    return [(f1+f2)*h/2., (F1+F2)*h/2.] # [dy, y] update

i = 0
y = 0
dy = 1
h = 0.1
k = m = 1
ylist = []
while i<100:
    array = rk2_step(k,m,y,dy)
    dy += array[0]
    y += array[1]
    #print y,dy
    ylist.append(y)
    i +=1
In [15]:
plt.plot(ylist)
Out[15]:
[<matplotlib.lines.Line2D at 0xb101ae0c>]
In []: