Wednesday, June 1, 2011

Solving ODEs using Mathematica

Originally Posted on  by hsauro

Solving ODEs using Mathematica

I have found that the documentation that comes with Mathematica is not always very helpful. At least it is not very helpful when you want to know the most common operations. One of those is solving systems of first order ordinary differential equations (odes) with initial conditions. I don’t know why but I always spend a little time reading the docs to figure out how to do this when I need this functionality. To help me and perhaps others, I give the Mathematica recipe here.

Here are two examples of how to solve a single ode and a simple system of two odes. The function we will use is DSolve[]. This function takes three arguments:

DSolve[{odes, initial conditions}, {variable names}, independent variable]

Note the curly brackets, they must be present. For example to solve the single ode with initial condition, y(0) = 1

  \[\frac{dy}{dt} = y (k_1 - k_2) - k_2\]

we need to input the following Mathematica command:

DSolve[{y'[t] == y[t] (k1 – k2) – k2, y[0] == 1}, y[t], t]

Note that the dependent variable y is denoted by y[t]. The derivative of the dependent variable is denoted by y’[t]. Also note how the initial condition is entered, y[0] == 1. Don’t forget to use == instead of = in the syntax. The solution yields:

  \[\left\{\left\{y[t]\to \frac{e^{(k_1-k_2) t} k_1+k_2-2 e^{(k_1-k_2) t} k_2}{k_1-k_2}\right\}\right\}\]

To solve a set of first order differential equations with initial equations, for example the two equations:

  \[\frac{dA}{dt} = v_o - k_1 A + k_2 B\]

  \[\frac{dB}{dt} = k_1 A - k_2 B - k_3 B\]

with initial conditions A(0) = 0 and B(0) = 0 we write the following Mathematica code where we enter the multiple equations inside the curly brackets separated by commas. Also note that because there is more than one dependent variable, we must also put these in curly brackets.

DSolve[{A'[t] == vo – k1 A[t] + k2 B[t], B’[t] == k1 A[t] – k2 B[t] – k3 B[t], A[0] == 0, B[0] == 0}, {A[t], B[t]}, t]

This will yield:

  \[\left\{\left\{A[t]\to \frac{v_o-e^{-k_1 t} v_o}{k_1},B[t]\to \frac{\left(k_1-e^{-k_3 t} k_1+\left(-1+e^{-k_1 t}\right) k_3\right) v_o}{(k_1-k_3) k_3}\right\}\right\}\]

No comments: