Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Solving Ordinary Differential Equations (ODEs) using Python
Simple differential equations can be solved numerically using the Euler-Cromer method, but more complicated differential equations may require a more sophisticated method. The "scipy" library for Python contains numerous functions for scientific computing and data analysis. It includes the function odeint for numerically solving sets of first-order, ordinary differential equations (ODEs) using a sophisticated algorithm. Any set of differential equations can be written in the required form. The example below calculates the solution to the second-order differential equation,
It can be rewritten as the two first-order differential equations,
and Notice that the first of these equations is really just a definition. In Python, the function and its derivative will be elements of an array. The function will be the first element (remember that the lowest index of an array is zero, not one) and the derivative will be the second element . The index indicates how many derivatives are taken of the function. In this notation, the differential equiations are
and The odeint function requires a function (called deriv in the example below) that will return the first derivative of each of element in the array. In other words, the first element returned is and the second element is , which are both functions of and . You must also provide initial values for and , which are placed in the array in the example below. Finally, the values of the times at which solutions are desired are provided in the array . Note that odeint returns the values of both the function and its derivative at each time in an array . The function is plotted versus time.
For a second example, suppose that you want to solve the following coupled, second-order differential equations,
and If we make the definitions, and then the two second-order equations can be written as the four first-order equations,
and These equations are now in a form necessary for the derivative function, w hich would be an array with four elements. Notice that the index of the array is not the number of derivatives of a single function in this case.
##Exercise
An example of a differential equation that exhibits chaotic behavior is
- Write the differential equation as a set of three first-order differential equations.
- Modify the example program to solve the equations with the initial conditions of , , and .
- Plot the results for for from 0 to 100.
Additional Documentation
Further information is available at: http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html