## Stopping the integration of an ODE at some condition

Posted February 27, 2013 at 02:30 PM | categories: ode | tags:

Updated February 27, 2013 at 02:30 PM

Matlab post In Post 968 we learned how to get the numerical solution to an ODE, and then to use the deval function to solve the solution for a particular value. The deval function uses interpolation to evaluate the solution at other valuse. An alternative approach would be to stop the ODE integration when the solution has the value you want. That can be done in Matlab by using an “event” function. You setup an event function and tell the ode solver to use it by setting an option.

Given that the concentration of a species A in a constant volume, batch reactor obeys this differential equation \(\frac{dC_A}{dt}=- k C_A^2\) with the initial condition \(C_A(t=0) = 2.3\) mol/L and \(k = 0.23\) L/mol/s, compute the time it takes for \(C_A\) to be reduced to 1 mol/L.

from pycse import * import numpy as np k = 0.23 Ca0 = 2.3 def dCadt(Ca, t): return -k * Ca**2 def stop(Ca, t): isterminal = True direction = 0 value = 1.0 - Ca return value, isterminal, direction tspan = np.linspace(0.0, 10.0) t, CA, TE, YE, IE = odelay(dCadt, Ca0, tspan, events=[stop], full_output=1) print 'At t = {0:1.2f} seconds the concentration of A is {1:1.2f} mol/L.'.format(t[-1], CA[-1])

At t = 2.46 seconds the concentration of A is 1.00 mol/L.

Copyright (C) 2013 by John Kitchin. See the License for information about copying.