python code to solve the following initial value problem ordinary differential equation using Euler method over the interval (0 10)

Solution 1:

Your output is essentially correct, but shifted by 1 (so e.g. your y10 is what the intended output calls y9) and not rounded to 4 decimal places.

There are 10 updates to y but you want to print 11 values. The way to do that is to either print the first y before the loop or print the final y after the loop. The following code shows the second approach:

y = 1
t = 0
h = 0.0001
iterates = [1]

for i in range(10):
    print(f'y{i} = {y:.4f}')
    y = y+h*(-y-y**2)
    iterates.append(y)
    t += h
print(f'y10 = {y:.4f}')

Note that this code simply using a scalar variable y as the variable in Euler's method (rather than an entry in an array. Ultimately a matter of taste, but the code seems cleaner that way.

The output is:

y0 = 1.0000
y1 = 0.9998
y2 = 0.9996
y3 = 0.9994
y4 = 0.9992
y5 = 0.9990
y6 = 0.9988
y7 = 0.9986
y8 = 0.9984
y9 = 0.9982
y10 = 0.9980

which matches the expected output.