How does one calculate the pH of an aqueous solution of a weak acid and a weak base?
Equations and variables

To calculate the proton concentration in a solution as given in the question the following five equations are used for the following five unknown variables: $\ce{[H+ ]}$, $\ce{[HA]}$, $\ce{[A- ]}$, $\ce{[HB]}$ and $\ce{[B- ]}$.

Ion balance:
$$ \ce{[H+ ]} = \ce{[A- ] + [B- ]} + \frac{K_\text{w}}{\ce{[H+ ]}} $$

Mass balances:
$$\begin{align}
\ce{[A]_{tot}} &amp;= \ce{[HA] + [A- ]} \\
\ce{[B]_{tot}} &amp;= \ce{[HB] + [B- ]} 
\end{align}$$

Law of mass action:
$$\begin{align}
K_\text{a, 1} &amp;= \frac{\ce{[H+ ][A- ]}}{\ce{[HA]}} \\
K_\text{a, 2} &amp;= \frac{\ce{[H+ ][B- ]}}{\ce{[HB]}}
\end{align}$$



Solution

Combining the above equations we get:
$$
\ce{[H+ ]} = \frac{K_\text{a, 1} \ce{[A]_{tot}} }{\ce{[H+ ]}+K_\text{a, 1}} + \frac{K_\text{a, 2} \ce{[B]_{tot}} }{\ce{[H+ ]}+K_\text{a, 2}} + \frac{K_\text{w}}{\ce{[H+ ]} }
$$

After some reforming we get a fourth-order polynomial for the proton concentration:
$$\begin{align}
0 = &amp; \ce{[H+ ]^4} + \ce{[H+ ]^3}(K_\text{a, 1} + K_\text{a, 2}) \\
  &amp;- \ce{[H+ ]^2}(\ce{[A]_{tot}} K_\text{a, 1} + \ce{[B]_{tot}} K_\text{a, 2} - K_\text{a, 1} K_\text{a, 2} + K_\text{w}) \\
 &amp; -\ce{[H+ ]}\left[ (\ce{[A]_{tot}} + \ce{[B]_{tot}}) K_\text{a, 1} K_\text{a, 2} + K_\text{w}(K_\text{a, 1} K_\text{a, 2}) \right] \\
 &amp; - K_\text{w} K_\text{a, 1} K_\text{a, 2}
\end{align}$$