Hi guys,
I have run into a problem implementing an simple algorithm to calculate the coefficients of chemic equation. The problem is actually as the title says I don´t know how to code this in php :evilgrin: .
I wrote already a parser for reaction-schemes,
so lets say we parsed
"KMnO4 + HCl --> MnCl2 + Cl2 + H2O + KCl"
(side a) --> (side b)
and know that we have O four times (O4) on side a on pos. 0 and Cl two times on side b on pos 0 and 1 for instance.
Of course the scheme is parsed into an array. I don´t think it is important to know the arraystructure I´ve chosen.
I would just like to get some hints on how to implement the following algorithm we can use to solve the equation:
We assume we can solve the equation using the coefficients abcdef like below:
a KMnO4 + b HCl --> c MnCl2 + d Cl2 + e H2O + f KCl
for K:
(1) a = f
for MG:
(2) a = c
for O:
(3) 4 a = e
for H:
(4) b = 2 e
for Cl:
(5) b = 2 c + 2 d + f
We just say a is 1, replace a with 1 and then have:
(1) 1 = f
(2) 1 = c
(3) 4 = e
(4) b = 2 e = 2 4 = 8
We use the calculated values below so we get:
(5) 8 = 2 + 2 d + 1
(5) 5 = 2 d
(5) 5
d = -
2
Now we almost got the final coefficients :
a = 1, b = 8, c = 1, d = 5/2, e = 4 und f = 1
We have to multiply all by 2 to get want we wanted:
a = 2, b = 16, c = 2, d = 5, e = 8 und f = 2
We replace the coefficients with the calculated values:
2 KMnO4 + 16 HCl --> 2 MnCl2 + 5 Cl2 + 8 H2O + 2 KCl
viola, solved!
So, is there any script you know which solves such equations.
If not, how could I implement the algorithm in php?
Well, maybe it´s a good idea to mention that I´m not that good in math heh.
Any help is greatly appreciated though. Note that this is a personal project 😉