Differential Equations by Euler’s Method

AIM: Write a Python program to find numerical solution of ordinary differential equations by Euler’s method.

Source Code:
# Euler method python program

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

# Euler method
def euler(x0,y0,xn,n):
 
# Calculating step size
  h = (xn-x0)/n
 
  print("-----------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("At x=%.4f, y=%.4f" %(xn,yn))

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(x0,y0,xn,step)
Output:
Enter  initial  conditions:
x0  =  0
y0  =  1
Enter  calculation  point: 
xn  =  1
Enter  number  of  steps:
Number  of  steps  =  5     
-----------SOLUTION-----------
------------------------------
x0            y0       slope      yn       
------------------------------
0.0000    1.0000    1.0000    1.2000
------------------------------
0.2000    1.2000    1.4000    1.4800
------------------------------
0.4000    1.4800    1.8800    1.8560
------------------------------
0.6000    1.8560    2.4560    2.3472
------------------------------
0.8000    2.3472    3.1472    2.9766
------------------------------
At  x=1.0000,  y=2.9766