Got Questions? Get Answers.
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Newton Raphson method for chemical equilibrium system

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 3 Aug, 2010 23:38:07

Message: 1 of 26

I am trying to solve a system of equations relating to a chemical equilibrium problem in the form or A*x = B, five equations and five unknowns. The A-matrix is 5x5 as is the Jacobian. I have no problem solving the current system; however, when I try to solve for a larger system I start running into problems. I was wondering if anyone could provide some suggestions on how to use this method for a larger system of equations, thus solving for more unknowns. My function for the Newton Raphson method is shown below. Please let me know how I could improve the code. It currently works well even with bad initial guesses for the 5x5 system, but fails when the system is larger than 5x5. When I run the problem for a 6x6 system, it converges but gives a warning that the matrix is close to singular or badly scaled. How can I fix this? I've read that incorporating a damping method with Newton
Raphson helps, but I am unsure of how to apply this to my problem.

function solution = Newton(Function,Jacobian,x_i,tol)
x = x_i;
error = 2*tol;
while error > tol
    F = feval(Function,x);
    error1 = max(abs(F));
    error2 = max(abs(F));
    J = feval(Jacobian,x);
    dx = J\(-F);
    i=1;
    while error2 >= error1||~isreal(F)
        xnew = x+0.5^i*dx;
        F = feval(Function,xnew);
        error2 = max(abs(F));
        i = i+1;
    end
    x = xnew;
    F = feval(Function,x);
    error = max(abs(F));
    disp(['error = ' num2str(error)])
end
solution = x;

Subject: Newton Raphson method for chemical equilibrium system

From: TideMan

Date: 3 Aug, 2010 23:58:19

Message: 2 of 26

On Aug 4, 11:38 am, "Gavin " <wigg...@gmail.com> wrote:
> I am trying to solve a system of equations relating to a chemical equilibrium problem in the form or A*x = B, five equations and five unknowns.  The A-matrix is 5x5 as is the Jacobian.  I have no problem solving the current system; however, when I try to solve for a larger system I start running into problems.  I was wondering if anyone could provide some suggestions on how to use this method for a larger system of equations, thus solving for more unknowns.  My function for the Newton Raphson method is shown below.  Please let me know how I could improve the code.  It currently works well even with bad initial guesses for the 5x5 system, but fails when the system is larger than 5x5.  When I run the problem for a 6x6 system, it converges but gives a warning that the matrix is close to singular or badly scaled.  How can I fix this?  I've read that incorporating a damping method with Newton
> Raphson helps, but I am unsure of how to apply this to my problem.
>
> function solution = Newton(Function,Jacobian,x_i,tol)
> x = x_i;
> error = 2*tol;
> while error > tol
>     F = feval(Function,x);
>     error1 = max(abs(F));
>     error2 = max(abs(F));
>     J = feval(Jacobian,x);
>     dx = J\(-F);
>     i=1;
>     while error2 >= error1||~isreal(F)
>         xnew = x+0.5^i*dx;
>         F = feval(Function,xnew);
>         error2 = max(abs(F));
>         i = i+1;
>     end
>     x = xnew;
>     F = feval(Function,x);
>     error = max(abs(F));
>     disp(['error = ' num2str(error)])
> end
> solution = x;

Just one comment on your code:
Apparently, you are restricting the increment in x to avoid moving
into the complex territory of F, yet you are using i as the counter
and exponent. This is foolish because next thing you'll be doing
something that assumes i is sqrt(-1). Believe me, this happens, and
it can be quite tricky to find the bug. Use something else for the
counter, like m, for example.

Other than that, your code looks good to me.
So, if it fails when you add another equation, it points to an error
in how you've assembled the Jacobian. Are you sure your algebra is
correct? It's easy to make a mistake when doing partial
differentiation of a complicated equation. All it takes is one stray
negative sign to screw everything up...............

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 4 Aug, 2010 03:28:04

Message: 3 of 26

TideMan <mulgor@gmail.com> wrote in message <ec2acf45-eb15-4a32-bc4d-4199af5dbbab@n19g2000prf.googlegroups.com>...
 
> Just one comment on your code:
> Apparently, you are restricting the increment in x to avoid moving
> into the complex territory of F, yet you are using i as the counter
> and exponent. This is foolish because next thing you'll be doing
> something that assumes i is sqrt(-1). Believe me, this happens, and
> it can be quite tricky to find the bug. Use something else for the
> counter, like m, for example.
>
> Other than that, your code looks good to me.
> So, if it fails when you add another equation, it points to an error
> in how you've assembled the Jacobian. Are you sure your algebra is
> correct? It's easy to make a mistake when doing partial
> differentiation of a complicated equation. All it takes is one stray
> negative sign to screw everything up...............

TideMan,

I changed the " i " in the code to " m " to avoid the assumption of i is sqrt(-1). This does not fix my problem. I also checked my Jacobian and everything seems to be calculated correctly. My problem seems to arise when certain values in the Jacobian become very large or very small compared to the other values in the matrix. I can provide my entire code if you are interested.

Gavin

Subject: Newton Raphson method for chemical equilibrium system

From: TideMan

Date: 4 Aug, 2010 03:46:39

Message: 4 of 26

On Aug 4, 3:28 pm, "Gavin " <wigg...@gmail.com> wrote:
> TideMan <mul...@gmail.com> wrote in message <ec2acf45-eb15-4a32-bc4d-4199af5db...@n19g2000prf.googlegroups.com>...
> > Just one comment on your code:
> > Apparently, you are restricting the increment in x to avoid moving
> > into the complex territory of F, yet you are using i as the counter
> > and exponent.  This is foolish because next thing you'll be doing
> > something that assumes i is sqrt(-1).  Believe me, this happens, and
> > it can be quite tricky to find the bug.  Use something else for the
> > counter, like m, for example.
>
> > Other than that, your code looks good to me.
> > So, if it fails when you add another equation, it points to an error
> > in how you've assembled the Jacobian.  Are you sure your algebra is
> > correct?  It's easy to make a mistake when doing partial
> > differentiation of a complicated equation.  All it takes is one stray
> > negative sign to screw everything up...............
>
> TideMan,
>
> I changed the " i " in the code to " m " to avoid the assumption of i is sqrt(-1).  This does not fix my problem.  I also checked my Jacobian and everything seems to be  calculated correctly.  My problem seems to arise when certain values in the Jacobian become very large or very small compared to the other values in the matrix.  I can provide my entire code if you are interested.
>
> Gavin

No, I'm not interested in looking at your code.
All I can tell you is that in 40 years since graduation, I've done a
lot of work using Newton Raphson and every time I've had a problem it
has been because I got the algebra wrong in assembling the Jacobian.
First, you need to check your partial differentiation.
Next, you need to check that you have correctly transcribed the
partial differentials into Matlab code.

Subject: Newton Raphson method for chemical equilibrium system

From: Roger Stafford

Date: 4 Aug, 2010 04:28:04

Message: 5 of 26

TideMan <mulgor@gmail.com> wrote in message <126edaf0-e1e5-4760-a737-6d680d5f9dfb@m17g2000prl.googlegroups.com>...
> No, I'm not interested in looking at your code.
> All I can tell you is that in 40 years since graduation, I've done a
> lot of work using Newton Raphson and every time I've had a problem it
> has been because I got the algebra wrong in assembling the Jacobian.
> First, you need to check your partial differentiation.
> Next, you need to check that you have correctly transcribed the
> partial differentials into Matlab code.
- - - - - - - - - -
  It is conceivable to me that the Newton-Raphson method for multiple dimensions could run into convergence problems with real-life situations. To take an example from geometry suppose you are seeking the point of tangency between a plane and a sphere. Suppose further that you wish to start the iteration with a point (x,y,z) near the tangency point but not necessarily constrained to either the plane or the sphere. (Admittedly this is not a wise approach for this problem.) The closer you get to the tangency point, the more nearly singular the Jacobian gets. Though I haven't tried this problem I suspect there would be real trouble finding the tangency point accurately using this approach.

  My training in chemical equilibria is too ancient to be certain, but I speculate that there may be some situations involving a nearly unstable point of equilibrium where an analogous difficulty with Newton-Raphson could arise. It would depend on the nature of the reaction rates involved.

Roger Stafford

Subject: Newton Raphson method for chemical equilibrium system

From: TideMan

Date: 4 Aug, 2010 04:50:02

Message: 6 of 26

On Aug 4, 4:28 pm, "Roger Stafford"
<ellieandrogerxy...@mindspring.com.invalid> wrote:
> TideMan <mul...@gmail.com> wrote in message <126edaf0-e1e5-4760-a737-6d680d5f9...@m17g2000prl.googlegroups.com>...
> > No, I'm not interested in looking at your code.
> > All I can tell you is that in 40 years since graduation, I've done a
> > lot of work using Newton Raphson and every time I've had a problem it
> > has been because I got the algebra wrong in assembling the Jacobian.
> > First, you need to check your partial differentiation.
> > Next, you need to check that you have correctly transcribed the
> > partial differentials into Matlab code.
>
> - - - - - - - - - -
>   It is conceivable to me that the Newton-Raphson method for multiple dimensions could run into convergence problems with real-life situations.  To take an example from geometry suppose you are seeking the point of tangency between a plane and a sphere.  Suppose further that you wish to start the iteration with a point (x,y,z) near the tangency point but not necessarily constrained to either the plane or the sphere.  (Admittedly this is not a wise approach for this problem.)  The closer you get to the tangency point, the more nearly singular the Jacobian gets.  Though I haven't tried this problem I suspect there would be real trouble finding the tangency point accurately using this approach.
>
>   My training in chemical equilibria is too ancient to be certain, but I speculate that there may be some situations involving a nearly unstable point of equilibrium where an analogous difficulty with Newton-Raphson could arise.  It would depend on the nature of the reaction rates involved.
>
> Roger Stafford

Well, in my experience with water waves (which admittedly are
generally pretty smooth in time and space), if something as robust as
Newton Raphson blows up it is pointing to a problem - the waves have
broken or the numerical scheme has gone unstable - but usually the
problem is not with Newton Raphson itself, which is what the OP is
assuming.

Subject: Newton Raphson method for chemical equilibrium system

From: Steve Amphlett

Date: 4 Aug, 2010 07:58:06

Message: 7 of 26

"Gavin " <wigging@gmail.com> wrote in message <i3a98v$lck$1@fred.mathworks.com>...
> I am trying to solve a system of equations relating to a chemical equilibrium problem in the form or A*x = B, five equations and five unknowns. The A-matrix is 5x5 as is the Jacobian. I have no problem solving the current system; however, when I try to solve for a larger system I start running into problems. I was wondering if anyone could provide some suggestions on how to use this method for a larger system of equations, thus solving for more unknowns. My function for the Newton Raphson method is shown below. Please let me know how I could improve the code. It currently works well even with bad initial guesses for the 5x5 system, but fails when the system is larger than 5x5. When I run the problem for a 6x6 system, it converges but gives a warning that the matrix is close to singular or badly scaled. How can I fix this? I've read that incorporating a damping method with
Newton
> Raphson helps, but I am unsure of how to apply this to my problem.
>
> function solution = Newton(Function,Jacobian,x_i,tol)
> x = x_i;
> error = 2*tol;
> while error > tol
> F = feval(Function,x);
> error1 = max(abs(F));
> error2 = max(abs(F));
> J = feval(Jacobian,x);
> dx = J\(-F);
> i=1;
> while error2 >= error1||~isreal(F)
> xnew = x+0.5^i*dx;
> F = feval(Function,xnew);
> error2 = max(abs(F));
> i = i+1;
> end
> x = xnew;
> F = feval(Function,x);
> error = max(abs(F));
> disp(['error = ' num2str(error)])
> end
> solution = x;

Gavin,

I assume you are still looking to solve your thermochemical equilibrium equations. If your technical German is up to it, you may find this link interesting:

http://elib.uni-stuttgart.de/opus/volltexte/2006/2725/pdf/Diss_Grill.pdf

- Steve

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 4 Aug, 2010 14:00:11

Message: 8 of 26


Thanks Steve, but I can't read German. I'm trying to solve the following system of equations:
where: CH4 = N(1), H2O = N(2), CO = N(3), H2 = N(4), CO2 = N(5), O2 = N(6)

CH4+CO+CO2-C = 0
4*CH4+2*H2O+2*H2-H = 0
H2O+CO+2*CO2+2*O2-O = 0
-LnKp1+2*log(P/sum(N))+log(N(3))+3*log(N(4))-log(N(1))-log(N(2)) = 0
-LnKp2+log(N(5))+log(N(4))-log(N(3))-log(N(2)) = 0
-LnKp3-0.5*log(P/sum(N))+log(N(2))-log(N(4))-0.5*log(N(6)) = 0

Known inputs are LnKp, C, H, O. Where LnKp is the log of the equilibrium constant for that particular reaction at the specified temperature.

Subject: Newton Raphson method for chemical equilibrium system

From: Torsten Hennig

Date: 4 Aug, 2010 14:55:44

Message: 9 of 26

>
> Thanks Steve, but I can't read German. I'm trying to
> solve the following system of equations:
> where: CH4 = N(1), H2O = N(2), CO = N(3), H2 = N(4),
> CO2 = N(5), O2 = N(6)
>
> CH4+CO+CO2-C = 0
> 4*CH4+2*H2O+2*H2-H = 0
> H2O+CO+2*CO2+2*O2-O = 0
> -LnKp1+2*log(P/sum(N))+log(N(3))+3*log(N(4))-log(N(1))
> -log(N(2)) = 0
> -LnKp2+log(N(5))+log(N(4))-log(N(3))-log(N(2)) = 0
> -LnKp3-0.5*log(P/sum(N))+log(N(2))-log(N(4))-0.5*log(N
> (6)) = 0
>
> Known inputs are LnKp, C, H, O. Where LnKp is the
> log of the equilibrium constant for that particular
> reaction at the specified temperature.

The first thing I'd do is to substitute N(i) = N~(i)^2
for i=1,...,6 to avoid negative arguments within
the logarithm.

Best wishes
Torsten.

Subject: Newton Raphson method for chemical equilibrium system

From: Maxx Chatsko

Date: 4 Aug, 2010 15:05:26

Message: 10 of 26

"Gavin " <wigging@gmail.com>
     I'm pretty handy with pchem and differentials. Would you mind sending me your code?
                Maxx

Subject: Newton Raphson method for chemical equilibrium system

From: Maxx Chatsko

Date: 4 Aug, 2010 15:19:05

Message: 11 of 26

"Maxx Chatsko" <chatskom@chemimage.com>

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 4 Aug, 2010 23:40:23

Message: 12 of 26

"Maxx Chatsko" <chatskom@chemimage.com> wrote in message <i3c0d8$1o4$1@fred.mathworks.com>...
> "Maxx Chatsko" <chatskom@chemimage.com>

Maxx,
I emailed the code to you. Let me know what you think. Thanks.

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 5 Aug, 2010 03:03:05

Message: 13 of 26

> The first thing I'd do is to substitute N(i) = N~(i)^2
> for i=1,...,6 to avoid negative arguments within
> the logarithm.
>
> Best wishes
> Torsten.

Torsten,

Substituting N(i) = N~(i)^2 for i=1...6 does not solve my problem. I still receive warnings for ill conditioned matrix. It also increases the number of iterations needed to solve the system.

Gavin

Subject: Newton Raphson method for chemical equilibrium system

From: Torsten Hennig

Date: 5 Aug, 2010 06:26:14

Message: 14 of 26

> > The first thing I'd do is to substitute N(i) =
> N~(i)^2
> > for i=1,...,6 to avoid negative arguments within
> > the logarithm.
> >
> > Best wishes
> > Torsten.
>
> Torsten,
>
> Substituting N(i) = N~(i)^2 for i=1...6 does not
> solve my problem. I still receive warnings for ill
> conditioned matrix. It also increases the number of
> iterations needed to solve the system.
>
> Gavin

Did you adjust the Jacobian matrix according to the substitution ?

Best wishes
Torsten.

Subject: Newton Raphson method for chemical equilibrium system

From: Darren Rowland

Date: 5 Aug, 2010 07:39:22

Message: 15 of 26

Torsten makes a good point about the need for updating the Jacobian.
I would also recommend writing a simple routine which calculates the Jacobian numerically, then compare your analytical version with the numerical.

Another common approach when working with chemical equilibria is to work only with the logarithms of the concentrations, i.e. let M = log(N) then run the NR scheme on M. You will need to update your Jacobian for this but the changes are only minor.

Hth
Darren

@ Maxx,
Trying to access www.chemimage.com I got the following error

Content Encoding Error
The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.

This is using Firefox 3.6.8

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 6 Aug, 2010 04:06:04

Message: 16 of 26

> > Gavin
>
> Did you adjust the Jacobian matrix according to the substitution ?
>
> Best wishes
> Torsten.

Torsten,
I have now adjusted the jacobian accordingly. However, I'm having issues with making the rest of the code consistent with changing to the N(i)^2 terms. I've posted links to my files below. Let me know how you would fix this. I am running the model with inputs of nC=2, nH=2, nO=4, T=500..1500, P=1. It runs fine at temperatures greater than 1200K but not so well below 1200K. The answers at 1300K should be yCH4=4.36e-8, yH2O=0.24882, yCO=0.24882, yH2=0.08451, yCO2=0.41785.
Gavin

I've posted my original m-file here... https://files.me.com/wigging/fh1src
and my modified (i.e. N(i)^2 ) file here... https://files.me.com/wigging/47n7xa

Subject: Newton Raphson method for chemical equilibrium system

From: Torsten Hennig

Date: 6 Aug, 2010 09:12:44

Message: 17 of 26

> > > Gavin
> >
> > Did you adjust the Jacobian matrix according to the
> substitution ?
> >
> > Best wishes
> > Torsten.
>
> Torsten,
> I have now adjusted the jacobian accordingly.
> However, I'm having issues with making the rest of
> f the code consistent with changing to the N(i)^2
> terms. I've posted links to my files below. Let me
> know how you would fix this. I am running the model
> with inputs of nC=2, nH=2, nO=4, T=500..1500, P=1.
> It runs fine at temperatures greater than 1200K but
> t not so well below 1200K. The answers at 1300K
> should be yCH4=4.36e-8, yH2O=0.24882, yCO=0.24882,
> yH2=0.08451, yCO2=0.41785.
> Gavin
>
> I've posted my original m-file here...
> https://files.me.com/wigging/fh1src
> and my modified (i.e. N(i)^2 ) file here...
> https://files.me.com/wigging/47n7xa

In every expression in the function F, you will have
to replace N(i) by N(i)^2.
This gives new functions F1,...,F6 which you will
have to partially differentiate with respect to
the N(i) to put the result in function Jac.
   
Best wishes
Torsten.

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 6 Aug, 2010 23:42:05

Message: 18 of 26

 > In every expression in the function F, you will have
> to replace N(i) by N(i)^2.
> This gives new functions F1,...,F6 which you will
> have to partially differentiate with respect to
> the N(i) to put the result in function Jac.
>
> Best wishes
> Torsten.

Torsten,
I've made the N(i)^2 changes to the F function but now I'm getting imaginary numbers. Something is definitely not right. I've updated the jacobian accordingly too. I've posted the latest file here:
https://files.me.com/wigging/6f6j7j

Gavin

Subject: Newton Raphson method for chemical equilibrium system

From: Torsten Hennig

Date: 7 Aug, 2010 10:15:30

Message: 19 of 26

I did not check your equations in detail, just
found two errors that I marked.

Best wishes
Torsten.


%%%%%%%%%%%%%% MAIN FUNCTION using Newton Raphson method %%%%%%%%%%%%%%%%
function gasf_Newton_6sJ
global T
global E
global Stoichiometry
global P
              
% input the flows of elements entering the system
nC = input('enter -> nC, mol = ');
nH = input('enter -> nH, mol = ');
nO = input('enter -> nO, mol = ');
E = [nC; nH; nO];
% set the temperature (K)
T = input('enter -> T, K = ');
% set the pressure (Po = 1 bar)
P = input('enter -> P, bar = ');
%set the stiociometry matrix
Stoichiometry = [1 0 1 0 1 0;...
                 4 2 0 2 0 0;...
                 0 1 1 0 2 2];

% solve the system of equations
[N] = Newton(@f,@jac,[1 1 1 1 1 1]',1e-6);

% outputs of system, moles and total moles
CH4 = sqrt(N(1));
H2O = sqrt(N(2));
CO = sqrt(N(3));
H2 = sqrt(N(4));
CO2 = sqrt(N(5));
O2 = sqrt(N(6));
nt = sqrt(sum(N));

>> nt must be the sum of the sqrt, not the
>> sqrt of the sum.

% mole fractions
yCH4 = CH4/nt
yH2O = H2O/nt
yCO = CO/nt
yH2 = H2/nt
yCO2 = CO2/nt
yO2 = O2/nt
ntt = yCH4 + yH2O + yCO + yH2 + yCO2 + yO2

%%%%%%%%%%%%%%%%%%%%%%%%%% Jacobian Matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Jac] = jac(N)

Jac(1:3,:) = [2*N(1), 0, 2*N(3), 0, 2*N(5), 0 ;...
              8*N(1), 4*N(2), 0, 4*N(4), 0, 0 ;...
              0, 2*N(2), 2*N(3), 0, 4*N(5), 4*N(6)];

% CH4 + H2O -> CO + 3*H2
% lnKp1 = 2*ln(P/nt) + ln(nCO) + 3*ln(nH2) - ln(nCH4) - ln(nH2O)
Jac(4,1) = (-4*N(1))/sum(N)-2/N(1);
Jac(4,2) = (-4*N(2))/sum(N)-2/N(2);
Jac(4,3) = (-4*N(3))/sum(N)+2/N(3);
Jac(4,4) = (-4*N(4))/sum(N)+6/N(4);
Jac(4,5) = (-4*N(5))/sum(N);
Jac(4,6) = (-4*N(6))/sum(N);
% CO + H2O -> CO2 + H2
% lnKp2 = ln(nCO2) + ln(nH2) - ln(nCO) - ln(nH2O)
Jac(5,1) = 0;
Jac(5,2) = -2/N(2);
Jac(5,3) = -2/N(3);
Jac(5,4) = 2/N(4);
Jac(5,5) = 2/N(5);
Jac(5,6) = 0;
% H2 + 0.5*O2 -> H2O
% lnKp4 = -0.5*ln(P/nt) + ln(nH2O) - ln(nH2) - 0.5*ln(nO2)
Jac(6,1) = N(1)/sum(N);
Jac(6,2) = N(2)/sum(N)+2/N(2);
Jac(6,3) = N(3)/sum(N);
Jac(6,4) = N(4)/sum(N)-2/N(4);
Jac(6,5) = N(5)/sum(N);
Jac(6,6) = N(6)/sum(N)-1/N(6);

>> You still use sum(N) in the Jac-routine although
>> you changed N to N.^2.

%%%%%%%%%%%%%%%%%%%%% Equilibrium Constants, lnKp %%%%%%%%%%%%%%%%%%%%%%%
function [LnKp1 LnKp2 LnKp3] = LnKp(T)
% database of temperatures, K
Tdb = [300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 ...
    1800 1900 2000];

% database of lnKp values from GasEq
lnKp1 = [-56.864 -35.9835 -23.2035 -14.5385 -8.2618 -3.5002 0.2359 3.2434...
    5.716 7.7828 9.536 11.04 12.3441 13.4842 14.4895 15.3812 16.1773 16.8919];
lnKp2 = [11.4575 7.3537 4.9302 3.3489 2.2479 1.4448 0.8381 0.3667 -0.0081...
    -0.3117 -0.5614 -0.7696 -0.9449 -1.0942 -1.2225 -1.3333 -1.4296 -1.5141];
lnKp3 = [91.6186 67.3317 52.7002 42.9072 35.8863 30.6019 26.479 23.1708...
    20.4575 18.191 16.2691 14.6193 13.187 11.9323 10.8234 9.8368 8.9531...
    8.1571];

% interpolate equilibrium constant
LnKp1 = interp1(Tdb,lnKp1,T,'spline','extrap');
LnKp2 = interp1(Tdb,lnKp2,T,'spline','extrap');
LnKp3 = interp1(Tdb,lnKp3,T,'spline','extrap');

%%%%%%%%%%%%%%%%%%%%% Set of Equations to Solve %%%%%%%%%%%%%%%%%%%%%%%%%
function [eq] = f(N)
global Stoichiometry
global E
global T
global P

% the element balance equations
eq(1:3) = Stoichiometry*N.^2 - E.^2;
% the equilibrium constants
[LnKp1 LnKp2 LnKp3] = LnKp(T);

% equilibrium equations
eq(4) = -LnKp1+2*log(P/sum(N.^2))+log(N(3)^2)+3*log(N(4)^2)-log(N(1)^2)-log(N(2)^2);
eq(5) = -LnKp2+log(N(5)^2)+log(N(4)^2)-log(N(3)^2)-log(N(2)^2);
eq(6) = -LnKp3-0.5*log(P/sum(N.^2))+log(N(2)^2)-log(N(4)^2)-0.5*log(N(6)^2);
eq = eq';

%%%%%%%%%%%%%%%%%%%%%%% Newton Raphson Method %%%%%%%%%%%%%%%%%%%%%%%%%%%
% modified from example in Numercial Methods in Chemical Engineering
function solution = Newton(Function,Jacobian,x_i,tol)
x = x_i;
error = 2*tol;
iter = 0;
while error > tol
    F = feval(Function,x);
    error1 = max(abs(F));
    error2 = max(abs(F));
    J = feval(Jacobian,x);
    dx = J\(-F);
    m = 1;
    while error2 >= error1||~isreal(F)
        xnew = x+0.5^m*dx;
        F = feval(Function,xnew);
        error2 = max(abs(F));
        m = m+1;
    end
    x = xnew;
    F = feval(Function,x);
    error = max(abs(F));
    iter = iter+1;
    disp(['error = ' num2str(error)])
    disp(['iter = ' num2str(iter)])
end
solution = x;

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 9 Aug, 2010 01:44:06

Message: 20 of 26

> % outputs of system, moles and total moles
> CH4 = sqrt(N(1));
> H2O = sqrt(N(2));
> CO = sqrt(N(3));
> H2 = sqrt(N(4));
> CO2 = sqrt(N(5));
> O2 = sqrt(N(6));
> nt = sqrt(sum(N));
> >> nt must be the sum of the sqrt, not the
> >> sqrt of the sum.
>
> Jac(6,4) = N(4)/sum(N)-2/N(4);
> Jac(6,5) = N(5)/sum(N);
> Jac(6,6) = N(6)/sum(N)-1/N(6);
> >> You still use sum(N) in the Jac-routine although
> >> you changed N to N.^2.

Torsten,
I've made the changes as you stated above and still get the wrong solutions. Imaginary numbers are still showing up somehow. Uploaded the latest m-file and the jacobian m-file that I'm using.
Gavin

m-file for model... https://files.me.com/wigging/10xkqn
jacobian m-file... https://files.me.com/wigging/cpg7p8

Subject: Newton Raphson method for chemical equilibrium system

From: Torsten Hennig

Date: 9 Aug, 2010 06:44:55

Message: 21 of 26

%%%%%%%%%%%%%% MAIN FUNCTION using Newton Raphson method %%%%%%%%%%%%%%%%
function gasf_Newton_6sJ
global T
global E
global Stoichiometry
global P
              
% input the flows of elements entering the system
nC = input('enter -> nC, mol = ');
nH = input('enter -> nH, mol = ');
nO = input('enter -> nO, mol = ');
E = [nC; nH; nO];
% set the temperature (K)
T = input('enter -> T, K = ');
% set the pressure (Po = 1 bar)
P = input('enter -> P, bar = ');
%set the stiociometry matrix
Stoichiometry = [1 0 1 0 1 0;...
                 4 2 0 2 0 0;...
                 0 1 1 0 2 2];

% solve the system of equations
[N] = Newton(@f,@jac,[1 1 1 1 1 1]',1e-6);

% outputs of system, moles and total moles
CH4 = sqrt(N(1));
H2O = sqrt(N(2));
CO = sqrt(N(3));
H2 = sqrt(N(4));
CO2 = sqrt(N(5));
O2 = sqrt(N(6));
nt = CH4+H2O+CO+H2+CO2+O2;

>> I was wrong in my last reply.
>> The last seven lines should read
>> CH4 = N(1)^2
>> H2O = N(2)^2
>> CO = N(3)^2
>> H2 = N(4)^2
>> CO2 = N(5)^2
>> O2 = N(6)^2
>> nt = CH4+H2O+CO+H2+CO2+O2

% mole fractions
yCH4 = CH4/nt
yH2O = H2O/nt
yCO = CO/nt
yH2 = H2/nt
yCO2 = CO2/nt
yO2 = O2/nt
ntt = yCH4 + yH2O + yCO + yH2 + yCO2 + yO2

%%%%%%%%%%%%%%%%%%%%%%%%%% Jacobian Matrix %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Jac] = jac(N)

sum = N(1)^2+N(2)^2+N(3)^2+N(4)^2+N(5)^2+N(6)^2;

Jac(1:3,:) = [2*N(1), 0, 2*N(3), 0, 2*N(5), 0 ;...
              8*N(1), 4*N(2), 0, 4*N(4), 0, 0 ;...
              0, 2*N(2), 2*N(3), 0, 4*N(5), 4*N(6)];

% CH4 + H2O -> CO + 3*H2
% lnKp1 = 2*ln(P/nt) + ln(nCO) + 3*ln(nH2) - ln(nCH4) - ln(nH2O)
Jac(4,1) = (-4*N(1))/sum-2/N(1);
Jac(4,2) = (-4*N(2))/sum-2/N(2);
Jac(4,3) = (-4*N(3))/sum+2/N(3);
Jac(4,4) = (-4*N(4))/sum+6/N(4);
Jac(4,5) = (-4*N(5))/sum;
Jac(4,6) = (-4*N(6))/sum;
% CO + H2O -> CO2 + H2
% lnKp2 = ln(nCO2) + ln(nH2) - ln(nCO) - ln(nH2O)
Jac(5,1) = 0;
Jac(5,2) = -2/N(2);
Jac(5,3) = -2/N(3);
Jac(5,4) = 2/N(4);
Jac(5,5) = 2/N(5);
Jac(5,6) = 0;
% H2 + 0.5*O2 -> H2O
% lnKp4 = -0.5*ln(P/nt) + ln(nH2O) - ln(nH2) - 0.5*ln(nO2)
Jac(6,1) = N(1)/sum;
Jac(6,2) = N(2)/sum+2/N(2);
Jac(6,3) = N(3)/sum;
Jac(6,4) = N(4)/sum-2/N(4);
Jac(6,5) = N(5)/sum;
Jac(6,6) = N(6)/sum-1/N(6);

%%%%%%%%%%%%%%%%%%%%% Equilibrium Constants, lnKp %%%%%%%%%%%%%%%%%%%%%%%
function [LnKp1 LnKp2 LnKp3] = LnKp(T)
% database of temperatures, K
Tdb = [300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 ...
    1800 1900 2000];

% database of lnKp values from GasEq
lnKp1 = [-56.864 -35.9835 -23.2035 -14.5385 -8.2618 -3.5002 0.2359 3.2434...
    5.716 7.7828 9.536 11.04 12.3441 13.4842 14.4895 15.3812 16.1773 16.8919];
lnKp2 = [11.4575 7.3537 4.9302 3.3489 2.2479 1.4448 0.8381 0.3667 -0.0081...
    -0.3117 -0.5614 -0.7696 -0.9449 -1.0942 -1.2225 -1.3333 -1.4296 -1.5141];
lnKp3 = [91.6186 67.3317 52.7002 42.9072 35.8863 30.6019 26.479 23.1708...
    20.4575 18.191 16.2691 14.6193 13.187 11.9323 10.8234 9.8368 8.9531...
    8.1571];

% interpolate equilibrium constant
LnKp1 = interp1(Tdb,lnKp1,T,'spline','extrap');
LnKp2 = interp1(Tdb,lnKp2,T,'spline','extrap');
LnKp3 = interp1(Tdb,lnKp3,T,'spline','extrap');

%%%%%%%%%%%%%%%%%%%%% Set of Equations to Solve %%%%%%%%%%%%%%%%%%%%%%%%%
function [eq] = f(N)
global Stoichiometry
global E
global T
global P

% the element balance equations
eq(1:3) = Stoichiometry*N.^2 - E.^2;

>> If your first version (before transforming
>> the variables) was correct, this should read
>> eq(1:3) = Stoichiometry*N.^2 - E;

% the equilibrium constants
[LnKp1 LnKp2 LnKp3] = LnKp(T);

% equilibrium equations
eq(4) = -LnKp1+2*log(P/sum(N.^2))+log(N(3)^2)+3*log(N(4)^2)-log(N(1)^2)-log(N(2)^2);
eq(5) = -LnKp2+log(N(5)^2)+log(N(4)^2)-log(N(3)^2)-log(N(2)^2);
eq(6) = -LnKp3-0.5*log(P/sum(N.^2))+log(N(2)^2)-log(N(4)^2)-0.5*log(N(6)^2);
eq = eq';

%%%%%%%%%%%%%%%%%%%%%%% Newton Raphson Method %%%%%%%%%%%%%%%%%%%%%%%%%%%
% modified from example in Numercial Methods in Chemical Engineering
function solution = Newton(Function,Jacobian,x_i,tol)
x = x_i;
error = 2*tol;
iter = 0;
while error > tol
    F = feval(Function,x);
    error1 = max(abs(F));
    error2 = max(abs(F));
    J = feval(Jacobian,x);
    dx = J\(-F);
    m = 1;
    while error2 >= error1||~isreal(F)
        xnew = x+0.5^m*dx;
        F = feval(Function,xnew);
        error2 = max(abs(F));
        m = m+1;
    end
    x = xnew;
    F = feval(Function,x);
    error = max(abs(F));
    iter = iter+1;
    disp(['error = ' num2str(error)])
    disp(['iter = ' num2str(iter)])
end
solution = x;

Best wishes
Torsten.

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 9 Aug, 2010 09:28:06

Message: 22 of 26

> % outputs of system, moles and total moles
> CH4 = sqrt(N(1));
> H2O = sqrt(N(2));
> CO = sqrt(N(3));
> H2 = sqrt(N(4));
> CO2 = sqrt(N(5));
> O2 = sqrt(N(6));
> nt = CH4+H2O+CO+H2+CO2+O2;
>
> >> I was wrong in my last reply.
> >> The last seven lines should read
> >> CH4 = N(1)^2
> >> H2O = N(2)^2
> >> CO = N(3)^2
> >> H2 = N(4)^2
> >> CO2 = N(5)^2
> >> O2 = N(6)^2
> >> nt = CH4+H2O+CO+H2+CO2+O2
>
> % the element balance equations
> eq(1:3) = Stoichiometry*N.^2 - E.^2;
>
> >> If your first version (before transforming
> >> the variables) was correct, this should read
> >> eq(1:3) = Stoichiometry*N.^2 - E;

Torsten,
I made the changes which seems to have taken care of the imaginary number problem. The model also runs from T = 700K-1500K with no warnings (original model only ran from T = 1200K-1500K with no warnings). However, the model fails to converge at T = 600K, and at T = 300K-500K matlab starts to give warnings again. The warning given at T = 300K is as follows:

> In gasf_Newton_6sJ>Newton at 126
   In gasf_Newton_6sJ at 23
   error = 1.4951e-06
   iter = 162
   Warning: Matrix is close to singular or badly scaled.
                Results may be inaccurate. RCOND = 1.137846e-35.

It would be great if I could avoid these warnings. My goal is to fix this so I can avoid problems when I use the model for a larger system. I've posted the current m-file if you want to run it and see if you get the same warning. My inputs are:
enter -> nC, mol = 2
enter -> nH, mol = 2
enter -> nO, mol = 4
enter -> T, K = 300
enter -> P, bar = 1

latest m-file is here... https://files.me.com/wigging/s2d25v

Gavin

Subject: Newton Raphson method for chemical equilibrium system

From: Torsten Hennig

Date: 9 Aug, 2010 09:55:23

Message: 23 of 26

> > % outputs of system, moles and total moles
> > CH4 = sqrt(N(1));
> > H2O = sqrt(N(2));
> > CO = sqrt(N(3));
> > H2 = sqrt(N(4));
> > CO2 = sqrt(N(5));
> > O2 = sqrt(N(6));
> > nt = CH4+H2O+CO+H2+CO2+O2;
> >
> > >> I was wrong in my last reply.
> > >> The last seven lines should read
> > >> CH4 = N(1)^2
> > >> H2O = N(2)^2
> > >> CO = N(3)^2
> > >> H2 = N(4)^2
> > >> CO2 = N(5)^2
> > >> O2 = N(6)^2
> > >> nt = CH4+H2O+CO+H2+CO2+O2
> >
> > % the element balance equations
> > eq(1:3) = Stoichiometry*N.^2 - E.^2;
> >
> > >> If your first version (before transforming
> > >> the variables) was correct, this should read
> > >> eq(1:3) = Stoichiometry*N.^2 - E;
>
> Torsten,
> I made the changes which seems to have taken care of
> the imaginary number problem. The model also runs
> from T = 700K-1500K with no warnings (original model
> only ran from T = 1200K-1500K with no warnings).
> However, the model fails to converge at T = 600K,
> , and at T = 300K-500K matlab starts to give warnings
> again. The warning given at T = 300K is as follows:
>
> > In gasf_Newton_6sJ>Newton at 126
> In gasf_Newton_6sJ at 23
> error = 1.4951e-06
> iter = 162
> Warning: Matrix is close to singular or badly
> dly scaled.
> Results may be inaccurate. RCOND =
> ccurate. RCOND = 1.137846e-35.
>
> It would be great if I could avoid these warnings.
> My goal is to fix this so I can avoid problems when
> n I use the model for a larger system. I've posted
> the current m-file if you want to run it and see if
> you get the same warning. My inputs are:
> enter -> nC, mol = 2
> enter -> nH, mol = 2
> enter -> nO, mol = 4
> enter -> T, K = 300
> enter -> P, bar = 1
>
> latest m-file is here...
> https://files.me.com/wigging/s2d25v
>
> Gavin

Just out of curiosity:
Why don't you use MATLAB's fsolve for your
nonlinear system of equations ?

Best wishes
Torsten.

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 9 Aug, 2010 12:47:04

Message: 24 of 26

I have tried using fsolve but ended up with incorrect results. Feel free to try with my system of equations and let me know if you get it to work correctly. I found that the newton raphson method gave more consistent answers and was easier to fix if problems arose.

Gavin

Subject: Newton Raphson method for chemical equilibrium system

From: Gavin

Date: 10 Aug, 2010 13:57:04

Message: 25 of 26

> > Gavin
>
> Just out of curiosity:
> Why don't you use MATLAB's fsolve for your
> nonlinear system of equations ?
>
> Best wishes
> Torsten.

Torsten,

I created a model using fsolve but still have problems at lower temperature ranges. At higher temperatures it will run but often gives incorrect answers. The warning that it gives at lower temperatures is the following...
>>Optimizer appears to be converging to a point which is not a root.
    Norm of relative change in X is less than max(options.TolX^2,eps) but
    sum-of-squares of function values is greater than or equal to sqrt(options.TolFun)
    Try again with a new starting guess.
I receive much better results when implementing the newton raphson method that we have been discussing.

Does anyone know how I can make the newton raphson model stable at lower temperature ranges?

Gavin

Subject: Newton Raphson method for chemical equilibrium system

From: Zaki

Date: 23 May, 2012 10:05:09

Message: 26 of 26

Dear Gavin,

Has this problem been solve?
If yes, which approach did you choose? The Fsolve or the newton Rahpson?

Thanks.

"Gavin" wrote in message <i3rlrg$lsm$1@fred.mathworks.com>...
> > > Gavin
> >
> > Just out of curiosity:
> > Why don't you use MATLAB's fsolve for your
> > nonlinear system of equations ?
> >
> > Best wishes
> > Torsten.
>
> Torsten,
>
> I created a model using fsolve but still have problems at lower temperature ranges. At higher temperatures it will run but often gives incorrect answers. The warning that it gives at lower temperatures is the following...
> >>Optimizer appears to be converging to a point which is not a root.
> Norm of relative change in X is less than max(options.TolX^2,eps) but
> sum-of-squares of function values is greater than or equal to sqrt(options.TolFun)
> Try again with a new starting guess.
> I receive much better results when implementing the newton raphson method that we have been discussing.
>
> Does anyone know how I can make the newton raphson model stable at lower temperature ranges?
>
> Gavin

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us