## Figure 4.31:

### Stochastic simulation of the first-order reactions A-> B-> C starting with 4000 Amolecules. ## Code for Figure 4.31

### main.m

```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76% Copyright (C) 2001, James B. Rawlings and John G. Ekerdt
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License as
% published by the Free Software Foundation; either version 2, or (at
% your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; see the file COPYING.  If not, write to
% the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
% MA 02111-1307, USA.

%
% add a stochastic simulation using Gillespie's algorithm
% jbr, 5/23/00
%
% Revised 7/24/2018
%
% example 1: A + B  --> C
%            C      --> A + B
%
% k(1) = 1;
% k(2) = 1/2;
% stoi = [-1 -1 1; 1 1 -1];
% [nrxs,nspec]=size(stoi);
% clear x
% x(1,1)= 1000;
% x(2,1)= 900;
% x(3,1)= 0;
%
% example 2: A --> B
%            B --> C
k(1) = 2;
k(2) = 1;
stoi = [-1 1 0; 0 -1 1];
[nrxs,nspec] = size(stoi);
nsim = 8000;
time = zeros (nsim+1, 1);
x = zeros (3, nsim+1);
x(1,1) = 4000;
x(2,1) = 0;
x(3,1) = 0;

%
stoiT = stoi';
time(1) = 0;
rand('seed', 2);

for n=1:nsim
r(1) = k(1)*x(1,n);
r(2) = k(2)*x(2,n);
rtot = sum(r);
p = rand(2,1);
tau = -log(p(1))/rtot;
time(n+1)=  time(n)+tau;

% determine which reaction (mth) is likely to occur
rcum = 0;
m = sum (cumsum (r) <= p(2)*rtot) + 1;
x(:,n+1) = x(:,n) + stoiT(:,m);
end

[ts,xs] = stairs(time, x');
table = [ts(:,1), xs];
save -ascii stoch_big.dat table;

if (~ strcmp (getenv ('OMIT_PLOTS'), 'true')) % PLOTTING
plot(table(:,1),table(:,2:4));
axis ([0, 5, 0, 4000]);
% TITLE
end % PLOTTING

```