简体   繁体   中英

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

i have this Question

Write a python code to solve the following initial value problem ordinary differential equation using Euler method over the interval (o 10) with 10 time steps. A) y'= -y -y^2; y(0)=1 If that exact solution was y(t) = 1/(-1+2e^t) What is the absolute error at y(10). now i have write this code

def pow_t(x,b):  
    t=1; 
    while (b):
        t*=x 
        b=b-1
    return t


def  absolute(): 
    y=[x for x in range(1,11)]
    
    h=0.0001 
    for i in range(1,10) :
       y[i]=y[i-1]+(h*(-1*y[i-1]-pow_t(y[i-1],2)))
       print("y",i,"=",y[i]) 
    
    exact = 0.0000227
    approx = y[9]
    absolute = exact - approx 
    print("abbsolute erroe = exact - approx ")
    print("abbsolute erroe = ",absolute)
   

print(absolute())

the expected output is this

and this is the actual result that I get

i need to set the first index of y list to 1 then fill the rest of list by the for loop, how can i code this?

It helps if you can know the closed form solution before you begin.

Equation: y' + y + y^2 = 0
Initial condition: y(0) = 1

This is a Bernoulli equation.

The closed form solution is:

y(t) = e^C1 / (e^C1 - e^t)

Applying the initial condition to solve for the constant C1:

y(0) = e^C1 / (e^C1 - 1) = 1

Your initial condition cannot be correct. There is no constant that satisfies the initial condition. Please check it and correct it.

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

One way to fix these issues is something like:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM