I am trying to find the solution of a differential equation at a point using the Euler method but I am getting a wrong answer. See my code below:
#Intial conditions
x0, y0 = 0, 1
h = 0.1 #step size
x_end = 1.0 #the value of x for which we want to know y
##The ODE function
def f(x,y):
return 1/(1 + x*x)
x_arr = np.arange(x0, x_end + h, h)
y_arr = np.zeros(x_arr.shape)
y_arr[0] = y0
for i, x in enumerate(x_arr[:-1]):
y_arr[i+1] = y_arr[i] + h*f(x, y_arr[i])
print("x array", x_arr)
print("y array", y_arr)
Output:
x array [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
y array [1. 1.1 1.1990099 1.29516375 1.38690687 1.47311376
1.55311376 1.62664317 1.69375727 1.75473288 1.8099815 ]
According to the python solution, y = 1.8099815 at x = 1.0 but I should be getting y = 1.85998149722679 at x = 1.0.
Am I doing something wrong? I am sure I am applying the Euler method correctly.