Question: Consider the generic initial value problem where y(t) is an unknown function of t: dy/dt=f(t,y),with y(t0)=y0. For instance, in the last exercise of the Week

Consider the generic initial value problem where y(t) is an unknown function of t:

dy/dt=f(t,y),with y(t0)=y0.

For instance, in the last exercise of the Week 7 tutorial, we had f(t,y)=y, and y(t0)=y(0)=0.

Write a function integrate(f, y0, t0, t1, N, algo) that takes as arguments a function 'f' (defined to take 2 arguments 't' and 'y'), an initial value 'y0', a start time 't0', an end time 't1' (t1>t0), the total number of time steps 'N' in the time interval [t0,t1] (such that t=(t1t0)/(N1) is the step size), and a string 'algo' to specify the numerical method used.

The function should return a Numpy vector 'y' of length 'N', i.e. a Numpy array of shape (N, ), containing the numerical solution of the initial value problem; the element 'y[n]' should contain the value of the computed solution yn at time step n, that is yny(t=t0+nt) where n=0,1,,N1. The method used to compute the solution should depend on the value of 'algo':

1. Use the forward Euler method with step size t if algo = 'EULER'.

2. Otherwise, use the built-in function 'solve_ivp()' (from scipy.integrate, scipy v1.5.1 https://docs.scipy.org/doc/scipy-1.5.1/reference/generated/scipy.integrate.solve_ivp.html#scipy.integrate.solve_ivp). Consider the documentation as to which algorithms can be used with this function, and make sure they are passed via the string 'algo'. Ensure that the solution is computed at times t=t0+nt,n=0,1,,N1.

You may wish to review Video 2 in the Week 4 course materials.

For example:

Test Result
import numpy as np from scipy.integrate import solve_ivp def f(t,y): return -y y0 = 1 t0 = 0 t1 = 10 y1 = integrate(f, y0, t0, t1, 1000, 'EULER') y2 = integrate(f, y0, t0, t1, 1000, 'RK45') print(f'{y1[-1]:.6e}') print(f'{y2[-1]:.6e}')
4.316906e-05 4.581596e-05

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!