# Euler's Method Python Program for Solving Ordinary Differential Equation

#### This program implements Euler's method for solving ordinary differential equation in Python programming language.

Output of this Python program is solution for dy/dx = x + y with initial condition y = 1 for x = 0 i.e. y(0) = 1 and we are trying to evaluate this differential equation at y = 1. ( Here y = 1 i.e. y(1) = ? is our calculation point)

## Python Source Code: Euler's Method

In this Python program x0 & y0 represents initial condition. xn is calculation point on which value of yn corresponding to xn is to be calculated using Euler's method. step represents number of finite step before reaching to xn.

``````
# Euler method python program

# function to be solved
def f(x,y):
return x+y

# or
# f = lambda x: x+y

# Euler method
def euler(x0,y0,xn,n):

# Calculating step size
h = (xn-x0)/n

print('\n-----------SOLUTION-----------')
print('------------------------------')
print('x0\ty0\tslope\tyn')
print('------------------------------')
for i in range(n):
slope = f(x0, y0)
yn = y0 + h * slope
print('%.4f\t%.4f\t%0.4f\t%.4f'% (x0,y0,slope,yn) )
print('------------------------------')
y0 = yn
x0 = x0+h

print('\nAt x=%.4f, y=%.4f' %(xn,yn))

# Inputs
print('Enter initial conditions:')
x0 = float(input('x0 = '))
y0 = float(input('y0 = '))

print('Enter calculation point: ')
xn = float(input('xn = '))

print('Enter number of steps:')
step = int(input('Number of steps = '))

# Euler method call
euler(x0,y0,xn,step)
``````

## Output

Output of above implementation to solve ordinary differential equation by Euler's method is:

```Enter initial conditions:
x0 = 0
y0 = 1
Enter calculation point:
xn = 1
Enter number of steps:
Number of steps = 10

-----------SOLUTION-----------
------------------------------
x0	y0	slope	yn
------------------------------
0.0000	1.0000	1.0000	1.1000
------------------------------
0.1000	1.1000	1.2000	1.2200
------------------------------
0.2000	1.2200	1.4200	1.3620
------------------------------
0.3000	1.3620	1.6620	1.5282
------------------------------
0.4000	1.5282	1.9282	1.7210
------------------------------
0.5000	1.7210	2.2210	1.9431
------------------------------
0.6000	1.9431	2.5431	2.1974
------------------------------
0.7000	2.1974	2.8974	2.4872
------------------------------
0.8000	2.4872	3.2872	2.8159
------------------------------
0.9000	2.8159	3.7159	3.1875
------------------------------

At x=1.0000, y=3.1875
```