0

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.

RUNN
  • 77
  • 7

1 Answers1

0

No, your result is correct for the step size. You can get this result of 10 steps shorter with

x = np.arange(0,1-1e-6,0.1); 
print(0.1*len(x), 1+0.1*sum(1/(1+x*x)))
## >>> 1.0    1.8099814972267896

The other value is for the next step at x=1.1

x = np.arange(0,1.1-1e-6,0.1); 
print(0.1*len(x), 1+0.1*sum(1/(1+x*x)))
## >>> 1.1    1.8599814972267898
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51