In [2]:
from numpy import *

In [3]:
def f(X):
x,y = X
return array([-y,x])

X = array([1.,0.])
T = 2*pi  # final time we want to get to
n = 10  # number of steps
h = T/n # time-step ("Delta-t")

print(0,X)
for i in range(n):
X += f(X)*h   # Euler step
t = (i+1)*h
print(t,X)

0 [ 1.  0.]
0.6283185307179586 [ 1.          0.62831853]
1.2566370614359172 [ 0.60521582  1.25663706]
1.8849555921538759 [-0.18435253  1.63690538]
2.5132741228718345 [-1.21285051  1.52107327]
3.141592653589793 [-2.16856903  0.75901682]
3.7699111843077517 [-2.64547336 -0.60353529]
4.39822971502571 [-2.26626096 -2.26573523]
5.026548245743669 [-0.84265753 -3.68966898]
5.654866776461628 [ 1.47562986 -4.21912632]
6.283185307179586 [ 4.12658512 -3.29196073]

In [6]:
import matplotlib.pyplot as plt
%matplotlib notebook

In [9]:
def f(X):
x,y = X
return array([-y,x])

X = array([1.,0.])
T = 2*pi  # final time we want to get to
n = 10  # number of steps
h = T/n # time-step ("Delta-t")

#print(0,X)
plt.subplot(111,aspect=1)

# draw exact solution
t = linspace(0,2*pi,300)
plt.plot(cos(t),sin(t),'k',alpha=0.5)
for i in range(n):
newX = X + f(X)*h   # Euler step
plt.plot([X[0],newX[0]],[X[1],newX[1]],'bo-')
X = newX
t = (i+1)*h
#print(t,X)

0 [ 1.  0.]
0.6283185307179586 [ 1.          0.62831853]
1.2566370614359172 [ 0.60521582  1.25663706]
1.8849555921538759 [-0.18435253  1.63690538]
2.5132741228718345 [-1.21285051  1.52107327]
3.141592653589793 [-2.16856903  0.75901682]
3.7699111843077517 [-2.64547336 -0.60353529]
4.39822971502571 [-2.26626096 -2.26573523]
5.026548245743669 [-0.84265753 -3.68966898]
5.654866776461628 [ 1.47562986 -4.21912632]
6.283185307179586 [ 4.12658512 -3.29196073]

In [11]:
def f(X):
x,y = X
return array([-y,x])

X = array([1.,0.])
T = 2*pi  # final time we want to get to
n = 100  # number of steps
h = T/n # time-step ("Delta-t")

#print(0,X)
plt.subplot(111,aspect=1)

# draw exact solution
t = linspace(0,2*pi,300)
plt.plot(cos(t),sin(t),'k',alpha=0.5)
for i in range(n):
newX = X + f(X)*h   # Euler step
plt.plot([X[0],newX[0]],[X[1],newX[1]],'bo-',ms=2,alpha=0.3)
X = newX
t = (i+1)*h
#print(t,X)

In [7]:
def f(X):
x,y = X
return array([-y,x])

X = array([1.,0.])
T = 2*pi  # final time we want to get to
n = 1000  # number of steps
h = T/n # time-step ("Delta-t")

#print(0,X)
plt.subplot(111,aspect=1)

# draw exact solution
t = linspace(0,2*pi,300)
plt.plot(cos(t),sin(t),'k',alpha=0.5)
for i in range(n):
newX = X + f(X)*h   # Euler step
plt.plot([X[0],newX[0]],[X[1],newX[1]],'bo-',ms=2,alpha=0.3)
X = newX
t = (i+1)*h
#print(t,X)
plt.show()