John_47 0 Newbie Poster

Hey, i'm having trouble with this question i was given. I'm tasked with improving a programme to calculate a differential.

Here is the code i am given, which i must improve.

def f(y,t):
    return -y + 1.0
def odestep(f,y,t,dt ):
    return y+dt*f(y,t)
    t =0; y=0; dt =0.2
tf =2.0; nsteps = int( tf/dt)
print t, y
for i in range( nsteps ):
    y= odestep(f,y,t,dt)
    t=(i +1)* dt
    print t, y

This method is obviously limited by the fact that dt must be very small to get a resonable accuracy.

I have been given advice on how to improve this:

  1. Find the slope at A.

  2. Use the slope at A, which we write as (dy/dt)A, to find the coordinates of the
    point B′.

  3. Use the values of y and t at B′ to compute the slope at B′, using the differential
    equation. Call this (dy/dt)B′ . This will not be the correct slope at B but using
    it will be better than ignoring the change of slope between A and B.

  4. Now throw away the value of y corresponding to B′ and compute a new corrected
    value for B using the average of the two slopes:

y(t +d t) = y(t)+0.5[(dy/dt)_A +(dy/dt)_B']dt

  1. Return y(t +d t) in the usual way.

I understand the principle of why and how this can be improved but I am unsure of how to code it.

Any help would be really appreciated, thanks John

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.