text:
Chemical equilibrium

In a chemical reaction, chemical equilibrium is the state in which both the reactants and products are present in concentrations which have no further tendency to change with time, so that there is no observable change in the properties of the system. This state results when the forward reaction proceeds at the same rate as the reverse reaction. The reaction rates of the forward and backward reactions are generally not zero, but they are equal. Thus, there are no net changes in the concentrations of the reactants and products. Such a state is known as dynamic equilibrium.

Historical introduction
The concept of chemical equilibrium was developed in 1803, after Berthollet found that some chemical reactions are reversible. For any reaction mixture to exist at equilibrium, the rates of the forward and backward (reverse) reactions must be equal. In the following chemical equation, arrows point both ways to indicate equilibrium. A and B are reactant chemical species, S and T are product species, and α, β, σ, and τ are the stoichiometric coefficients of the respective reactants and products:
 * α A + β B σ S + τ T

The equilibrium concentration position of a reaction is said to lie "far to the right" if, at equilibrium, nearly all the reactants are consumed. Conversely the equilibrium position is said to be "far to the left" if hardly any product is formed from the reactants.

Guldberg and Waage (1865), building on Berthollet's ideas, proposed the law of mass action:

where A, B, S and T are active masses and k+ and k− are rate constants. Since at equilibrium forward and backward rates are equal:

and the ratio of the rate constants is also a constant, now known as an equilibrium constant.

By convention, the products form the numerator. However, the law of mass action is valid only for concerted one-step reactions that proceed through a single transition state and is not valid in general because rate equations do not, in general, follow the stoichiometry of the reaction as Guldberg and Waage had proposed (see, for example, nucleophilic aliphatic substitution by SN1 or reaction of hydrogen and bromine to form hydrogen bromide). Equality of forward and backward reaction rates, however, is a necessary condition for chemical equilibrium, though it is not sufficient to explain why equilibrium occurs.

Despite the limitations of this derivation, the equilibrium constant for a reaction is indeed a constant, independent of the activities of the various species involved, though it does depend on temperature as observed by the van 't Hoff equation. Adding a catalyst will affect both the forward reaction and the reverse reaction in the same way and will not have an effect on the equilibrium constant. The catalyst will speed up both reactions thereby increasing the speed at which equilibrium is reached.

Although the macroscopic equilibrium concentrations are constant in time, reactions do occur at the molecular level. For example, in the case of acetic acid dissolved in water and forming acetate and hydronium ions,
 * CH3CO2H + H2O <-> CH3CO2- + H3O+

a proton may hop from one molecule of acetic acid onto a water molecule and then onto an acetate anion to form another molecule of acetic acid and leaving the number of acetic acid molecules unchanged. This is an example of dynamic equilibrium. Equilibria, like the rest of thermodynamics, are statistical phenomena, averages of microscopic behavior.

Le Châtelier's principle (1884) predicts the behavior of an equilibrium system when changes to its reaction conditions occur. If a dynamic equilibrium is disturbed by changing the conditions, the position of equilibrium moves to partially reverse the change. For example, adding more S (to the chemical reaction above) from the outside will cause an excess of products, and the system will try to counteract this by increasing the reverse reaction and pushing the equilibrium point backward (though the equilibrium constant will stay the same).

If mineral acid is added to the acetic acid mixture, increasing the concentration of hydronium ion, the amount of dissociation must decrease as the reaction is driven to the left in accordance with this principle. This can also be deduced from the equilibrium constant expression for the reaction:

If {H3O+} increases {CH3CO2H} must increase and CH3CO2- must decrease. The H2O is left out, as it is the solvent and its concentration remains high and nearly constant.

A quantitative version is given by the reaction quotient.

J. W. Gibbs suggested in 1873 that equilibrium is attained when the Gibbs free energy of the system is at its minimum value (assuming the reaction is carried out at a constant temperature and pressure). What this means is that the derivative of the Gibbs energy with respect to reaction coordinate (a measure of the extent of reaction that has occurred, ranging from zero for all reactants to a maximum for all products) vanishes (because dG = 0), signaling a stationary point. This derivative is called the reaction Gibbs energy (or energy change) and corresponds to the difference between the chemical potentials of reactants and products at the composition of the reaction mixture. This criterion is both necessary and sufficient. If a mixture is not at equilibrium, the liberation of the excess Gibbs energy (or Helmholtz energy at constant volume reactions) is the "driving force" for the composition of the mixture to change until equilibrium is reached. The equilibrium constant can be related to the standard Gibbs free energy change for the reaction by the equation

 * $$\Delta_rG^\ominus = -RT \ln K_\mathrm{eq}$$

where R is the universal gas constant and T the temperature.

When the reactants are dissolved in a medium of high ionic strength the quotient of activity coefficients may be taken to be constant. In that case the concentration quotient, Kc,

where [A] is the concentration of A, etc., is independent of the analytical concentration of the reactants. For this reason, equilibrium constants for solutions are usually determined in media of high ionic strength. Kc varies with ionic strength, temperature and pressure (or volume). Likewise Kp for gases depends on partial pressure. These constants are easier to measure and encountered in high-school chemistry courses.

Thermodynamics
At constant temperature and pressure, one must consider the Gibbs free energy, G, while at constant temperature and volume, one must consider the Helmholtz free energy, A, for the reaction; and at constant internal energy and volume, one must consider the entropy, S, for the reaction.

The constant volume case is important in geochemistry and atmospheric chemistry where pressure variations are significant. Note that, if reactants and products were in standard state (completely pure), then there would be no reversibility and no equilibrium. Indeed, they would necessarily occupy disjoint volumes of space. The mixing of the products and reactants contributes a large entropy increase (known as entropy of mixing) to states containing equal mixture of products and reactants and gives rise to a distinctive minimum in the Gibbs energy as a function of the extent of reaction. The standard Gibbs energy change, together with the Gibbs energy of mixing, determine the equilibrium state.

In this article only the constant pressure case is considered. The relation between the Gibbs free energy and the equilibrium constant can be found by considering chemical potentials.

At constant temperature and pressure in the absence of an applied voltage, the Gibbs free energy, G, for the reaction depends only on the extent of reaction: ξ (Greek letter xi), and can only decrease according to the second law of thermodynamics. It means that the derivative of G with respect to ξ must be negative if the reaction happens; at the equilibrium this derivative is equal to zero.
 * $$\left(\frac {dG}{d\xi}\right)_{T,p} = 0~$$:   equilibrium

In order to meet the thermodynamic condition for equilibrium, the Gibbs energy must be stationary, meaning that the derivative of G with respect to the extent of reaction, ξ, must be zero. It can be shown that in this case, the sum of chemical potentials times the stoichiometric coefficients of the products is equal to the sum of those corresponding to the reactants. Therefore, the sum of the Gibbs energies of the reactants must be the equal to the sum of the Gibbs energies of the products.
 * $$ \alpha \mu_\mathrm{A} + \beta \mu_\mathrm{B} = \sigma \mu_\mathrm{S} + \tau \mu_\mathrm{T} \,$$

where μ is in this case a partial molar Gibbs energy, a chemical potential. The chemical potential of a reagent A is a function of the activity, {A} of that reagent.

 * $$ \mu_\mathrm{A} = \mu_{A}^{\ominus} + RT \ln\{\mathrm{A}\} \,$$

(where μ$o A$ is the standard chemical potential).

The definition of the Gibbs energy equation interacts with the fundamental thermodynamic relation to produce

 * $$ dG = Vdp-SdT+\sum_{i=1}^k \mu_i dN_i $$.

Inserting dNi = νi dξ into the above equation gives a stoichiometric coefficient ($$ \nu_i~$$) and a differential that denotes the reaction occurring to an infinitesimal extent (dξ). At constant pressure and temperature the above equations can be written as

 * $$\left(\frac {dG}{d\xi}\right)_{T,p} = \sum_{i=1}^k \mu_i \nu_i = \Delta_\mathrm{r}G_{T,p}$$

which is the "Gibbs free energy change for the reaction'''. This results in:

 * $$ \Delta_\mathrm{r}G_{T,p} = \sigma \mu_\mathrm{S} + \tau \mu_\mathrm{T} - \alpha \mu_\mathrm{A} - \beta \mu_\mathrm{B} \,$$.

By substituting the chemical potentials:

 * $$ \Delta_\mathrm{r}G_{T,p} = ( \sigma \mu_\mathrm{S}^{\ominus} + \tau \mu_\mathrm{T}^{\ominus} ) - ( \alpha \mu_\mathrm{A}^{\ominus} + \beta \mu_\mathrm{B}^{\ominus} ) + ( \sigma RT \ln\{\mathrm{S}\} + \tau RT \ln\{\mathrm{T}\} ) - ( \alpha RT \ln\{\mathrm{A}\} + \beta RT \ln \{\mathrm{B}\} ) $$,

the relationship becomes:

 * $$ \Delta_\mathrm{r}G_{T,p}=\sum_{i=1}^k \mu_i^\ominus \nu_i + RT \ln \frac{\{\mathrm{S}\}^\sigma \{\mathrm{T}\}^\tau} {\{\mathrm{A}\}^\alpha \{\mathrm{B}\}^\beta} $$
 * $$\sum_{i=1}^k \mu_i^\ominus \nu_i = \Delta_\mathrm{r}G^{\ominus}$$:

which is the standard Gibbs energy change for the reaction that can be calculated using thermodynamical tables. The reaction quotient is defined as:
 * $$ Q_\mathrm{r} = \frac{\{\mathrm{S}\}^\sigma \{\mathrm{T}\}^\tau} {\{\mathrm{A}\}^\alpha \{\mathrm{B}\}^\beta}  $$

Therefore,
 * $$\left(\frac {dG}{d\xi}\right)_{T,p} = \Delta_\mathrm{r}G_{T,p}= \Delta_\mathrm{r}G^{\ominus} + RT \ln Q_\mathrm{r} $$

At equilibrium:
 * $$\left(\frac {dG}{d\xi}\right)_{T,p} = \Delta_\mathrm{r}G_{T,p} = 0 $$

leading to:

 * $$ 0 = \Delta_\mathrm{r}G^{\ominus} + RT \ln K_\mathrm{eq} $$

and
 * $$ \Delta_\mathrm{r}G^{\ominus} = -RT \ln K_\mathrm{eq} $$

Obtaining the value of the standard Gibbs energy change, allows the calculation of the equilibrium constant.

Addition of reactants or products
For a reactional system at equilibrium: Qr = Keq; ξ = ξeq.
 * If the activities of constituents are modified, the value of the reaction quotient changes and becomes different from the equilibrium constant: Qr ≠ Keq $$\left(\frac {dG}{d\xi}\right)_{T,p} = \Delta_\mathrm{r}G^{\ominus} + RT \ln Q_\mathrm{r}~$$ and $$\Delta_\mathrm{r}G^{\ominus} = - RT \ln K_{eq}~$$ then $$\left(\frac {dG}{d\xi}\right)_{T,p} = RT \ln \left(\frac {Q_\mathrm{r}}{K_\mathrm{eq}}\right)~$$
 * If activity of a reagent i increases $$Q_\mathrm{r} = \frac{\prod (a_j)^{\nu_j}}{\prod(a_i)^{\nu_i}}~,$$ the reaction quotient decreases. Then $$Q_\mathrm{r} < K_\mathrm{eq}~$$ and $$\left(\frac {dG}{d\xi}\right)_{T,p} < 0~$$ The reaction will shift to the right (i.e. in the forward direction, and thus more products will form).
 * If activity of a product j increases, then $$Q_\mathrm{r} > K_\mathrm{eq}~$$ and $$\left(\frac {dG}{d\xi}\right)_{T,p} >0~$$ The reaction will shift to the left (i.e. in the reverse direction, and thus less products will form).

Note that activities and equilibrium constants are dimensionless numbers.

Treatment of activity
The expression for the equilibrium constant can be rewritten as the product of a concentration quotient, Kc and an activity coefficient quotient, Γ.
 * $$K=\frac{[\mathrm{S}] ^\sigma [\mathrm{T}]^\tau ... } {[\mathrm{A}]^\alpha [\mathrm{B}]^\beta ...}

\times \frac{{\gamma_\mathrm{S}} ^\sigma {\gamma_\mathrm{T}}^\tau ... } {{\gamma_\mathrm{A}}^\alpha {\gamma_\mathrm{B}}^\beta ...} = K_\mathrm{c} \Gamma$$

[A] is the concentration of reagent A, etc. It is possible in principle to obtain values of the activity coefficients, γ. For solutions, equations such as the Debye–Hückel equation or extensions such as Davies equation Specific ion interaction theory or Pitzer equations may be used.Software (below) However this is not always possible. It is common practice to assume that Γ is a constant, and to use the concentration quotient in place of the thermodynamic equilibrium constant. It is also general practice to use the term equilibrium constant instead of the more accurate concentration quotient. This practice will be followed here.

For reactions in the gas phase partial pressure is used in place of concentration and fugacity coefficient in place of activity coefficient. In the real world, for example, when making ammonia in industry, fugacity coefficients must be taken into account. Fugacity, f, is the product of partial pressure and fugacity coefficient. The chemical potential of a species in the real gas phase is given by
 * $$\mu = \mu^{\ominus} + RT \ln \left( \frac{f}{\mathrm{bar}} \right) = \mu^{\ominus} + RT \ln \left( \frac{p}{\mathrm{bar}} \right) + RT \ln \gamma $$

so the general expression defining an equilibrium constant is valid for both solution and gas phases.

Concentration quotients
In aqueous solution, equilibrium constants are usually determined in the presence of an "inert" electrolyte such as sodium nitrate, NaNO3, or potassium perchlorate, KClO4. The ionic strength of a solution is given by
 * $$ I = \frac12\sum_{i=1}^N c_i z_i^2 $$

where ci and zi stand for the concentration and ionic charge of ion type i, and the sum is taken over all the N types of charged species in solution. When the concentration of dissolved salt is much higher than the analytical concentrations of the reagents, the ions originating from the dissolved salt determine the ionic strength, and the ionic strength is effectively constant. Since activity coefficients depend on ionic strength, the activity coefficients of the species are effectively independent of concentration. Thus, the assumption that Γ is constant is justified. The concentration quotient is a simple multiple of the equilibrium constant.
 * $$ K_\mathrm{c} = \frac{K}{\Gamma} $$

However, Kc will vary with ionic strength. If it is measured at a series of different ionic strengths, the value can be extrapolated to zero ionic strength. The concentration quotient obtained in this manner is known, paradoxically, as a thermodynamic equilibrium constant.

Before using a published value of an equilibrium constant in conditions of ionic strength different from the conditions used in its determination, the value should be adjustedSoftware (below).

Metastable mixtures
A mixture may appear to have no tendency to change, though it is not at equilibrium. For example, a mixture of SO2 and O2 is metastable as there is a kinetic barrier to formation of the product, SO3.
 * 2 SO2 + O2 2 SO3

The barrier can be overcome when a catalyst is also present in the mixture as in the contact process, but the catalyst does not affect the equilibrium concentrations.

Likewise, the formation of bicarbonate from carbon dioxide and water is very slow under normal conditions
 * CO2 + 2 H2O <-> HCO3- + H3O+

but almost instantaneous in the presence of the catalytic enzyme carbonic anhydrase.

Pure substances
When pure substances (liquids or solids) are involved in equilibria their activities do not appear in the equilibrium constant because their numerical values are considered one.

Applying the general formula for an equilibrium constant to the specific case of a dilute solution of acetic acid in water one obtains
 * CH3CO2H + H2O CH3CO2− + H3O+

 * $$K_\mathrm{c}=\frac \mathrm{[{CH_3CO_2}^-][{H_3O}^+]} \mathrm{[{CH_3CO_2H}][{H_2O}]}$$

For all but very concentrated solutions, the water can be considered a "pure" liquid, and therefore it has an activity of one. The equilibrium constant expression is therefore usually written as
 * $$K=\frac \mathrm{[{CH_3CO_2}^-][{H_3O}^+]} \mathrm{[{CH_3CO_2H}]} = K_\mathrm{c}$$.

A particular case is the self-ionization of water

 * 2 H2O H3O+ + OH−

Because water is the solvent, and has an activity of one, the self-ionization constant of water is defined as

 * $$K_\mathrm{w} = \mathrm{[H^+][OH^-]}$$

It is perfectly legitimate to write [H+] for the hydronium ion concentration, since the state of solvation of the proton is constant (in dilute solutions) and so does not affect the equilibrium concentrations. Kw varies with variation in ionic strength and/or temperature.

The concentrations of H+ and OH− are not independent quantities. Most commonly [OH−] is replaced by Kw[H+]−1 in equilibrium constant expressions which would otherwise include hydroxide ion.

Solids also do not appear in the equilibrium constant expression, if they are considered to be pure and thus their activities taken to be one. An example is the Boudouard reaction:

 * 2 CO CO2 + C

for which the equation (without solid carbon) is written as:

 * $$K_\mathrm{c}=\frac \mathrm{[CO_2]} \mathrm{[CO]^2}$$

Multiple equilibria
Consider the case of a dibasic acid H2A. When dissolved in water, the mixture will contain H2A, HA− and A2−. This equilibrium can be split into two steps in each of which one proton is liberated. K1 and K2 are examples of stepwise equilibrium constants. The overall equilibrium constant, βD, is product of the stepwise constants.

Note that these constants are dissociation constants because the products on the right hand side of the equilibrium expression are dissociation products. In many systems, it is preferable to use association constants. β1 and β2 are examples of association constants. Clearly $β_{1} = 1⁄K_{2}$ and $β_{2} = 1⁄β_{D}$; $log β_{1} = pK_{2}$ and $log β_{2} = pK_{2} + pK_{1}$ For multiple equilibrium systems, also see: theory of Response reactions.

Effect of temperature
The effect of changing temperature on an equilibrium constant is given by the van 't Hoff equation
 * $$\frac {d\ln K} {dT} = \frac{\Delta H_\mathrm{m}^\ominus} {RT^2}$$

Thus, for exothermic reactions (ΔH is negative), K decreases with an increase in temperature, but, for endothermic reactions, (ΔH is positive) K increases with an increase temperature. An alternative formulation is
 * $$\frac {d\ln K} {d(T^{-1})} = -\frac{\Delta H_\mathrm{m}^\ominus} {R}$$

At first sight this appears to offer a means of obtaining the standard molar enthalpy of the reaction by studying the variation of K with temperature. In practice, however, the method is unreliable because error propagation almost always gives very large errors on the values calculated in this way.

Effect of electric and magnetic fields
The effect of electric field on equilibrium has been studied by Manfred Eigen among others.

Types of equilibrium
Equilibrium can be broadly classified as heterogeneous and homogeneous equilibrium. Homogeneous equilibrium consists of reactants and products belonging in the same phase whereas heterogeneous equilibrium comes into play for reactants and products in different phases.
 * In the gas phase: rocket engines
 * The industrial synthesis such as ammonia in the Haber–Bosch process (depicted right) takes place through a succession of equilibrium steps including adsorption processes
 * Atmospheric chemistry
 * Seawater and other natural waters: chemical oceanography
 * Distribution between two phases
 * log D distribution coefficient: important for pharmaceuticals where lipophilicity is a significant property of a drug
 * Liquid–liquid extraction, Ion exchange, Chromatography
 * Solubility product
 * Uptake and release of oxygen by hemoglobin in blood
 * Acid–base equilibria: acid dissociation constant, hydrolysis, buffer solutions, indicators, acid–base homeostasis
 * Metal–ligand complexation: sequestering agents, chelation therapy, MRI contrast reagents, Schlenk equilibrium
 * Adduct formation: host–guest chemistry, supramolecular chemistry, molecular recognition, dinitrogen tetroxide
 * In certain oscillating reactions, the approach to equilibrium is not asymptotically but in the form of a damped oscillation.
 * The related Nernst equation in electrochemistry gives the difference in electrode potential as a function of redox concentrations.
 * When molecules on each side of the equilibrium are able to further react irreversibly in secondary reactions, the final product ratio is determined according to the Curtin–Hammett principle.

In these applications, terms such as stability constant, formation constant, binding constant, affinity constant, association constant and dissociation constant are used. In biochemistry, it is common to give units for binding constants, which serve to define the concentration units used when the constant's value was determined.

Composition of a mixture
When the only equilibrium is that of the formation of a 1:1 adduct as the composition of a mixture, there are many ways that the composition of a mixture can be calculated. For example, see ICE table for a traditional method of calculating the pH of a solution of a weak acid.

There are three approaches to the general calculation of the composition of a mixture at equilibrium.

 * 1) The most basic approach is to manipulate the various equilibrium constants until the desired concentrations are expressed in terms of measured equilibrium constants (equivalent to measuring chemical potentials) and initial conditions.
 * 2) Minimize the Gibbs energy of the system.
 * 3) Satisfy the equation of mass balance. The equations of mass balance are simply statements that demonstrate that the total concentration of each reactant must be constant by the law of conservation of mass.

Mass-balance equations
In general, the calculations are rather complicated or complex. For instance, in the case of a dibasic acid, H2A dissolved in water the two reactants can be specified as the conjugate base, A2−, and the proton, H+. The following equations of mass-balance could apply equally well to a base such as 1,2-diaminoethane, in which case the base itself is designated as the reactant A:
 * $$T_\mathrm{A} = \mathrm{[A] + [HA] +[H_2A]} \,$$
 * $$T_\mathrm{H} = \mathrm{[H] + [HA] + 2[H_2A] - [OH]} \,$$

with TA the total concentration of species A. Note that it is customary to omit the ionic charges when writing and using these equations.

When the equilibrium constants are known and the total concentrations are specified there are two equations in two unknown "free concentrations" [A] and [H]. This follows from the fact that [HA] = β1[A][H], [H2A] = β2[A][H]2 and [OH] = Kw[H]−1

 * $$ T_\mathrm{A} = \mathrm{[A]} + \beta_1\mathrm{[A][H]} + \beta_2\mathrm{[A][H]}^2 \,$$
 * $$ T_\mathrm{H} = \mathrm{[H]} + \beta_1\mathrm{[A][H]} + 2\beta_2\mathrm{[A][H]}^2 - K_w[\mathrm H]^{-1} \,$$

so the concentrations of the "complexes" are calculated from the free concentrations and the equilibrium constants. General expressions applicable to all systems with two reagents, A and B would be
 * $$T_\mathrm{A}=[\mathrm A]+\sum_i p_i \beta_i[\mathrm A]^{p_i}[\mathrm B]^{q_i}$$
 * $$T_\mathrm{B}=[\mathrm B]+\sum_i q_i \beta_i[\mathrm A]^{p_i}[\mathrm B]^{q_i}$$

It is easy to see how this can be extended to three or more reagents.

Polybasic acids
The composition of solutions containing reactants A and H is easy to calculate as a function of p[H]. When [H] is known, the free concentration [A] is calculated from the mass-balance equation in A.

The diagram alongside, shows an example of the hydrolysis of the aluminium Lewis acid Al3+(aq) shows the species concentrations for a 5 × 10−6 M solution of an aluminium salt as a function of pH. Each concentration is shown as a percentage of the total aluminium.

Solution and precipitation
The diagram above illustrates the point that a precipitate that is not one of the main species in the solution equilibrium may be formed. At pH just below 5.5 the main species present in a 5 μM solution of Al3+ are aluminium hydroxides Al(OH)2+, AlOH2+ and Al13(OH)32(7+), but on raising the pH Al(OH)3 precipitates from the solution. This occurs because Al(OH)3 has a very large lattice energy. As the pH rises more and more Al(OH)3 comes out of solution. This is an example of Le Châtelier's principle in action: Increasing the concentration of the hydroxide ion causes more aluminium hydroxide to precipitate, which removes hydroxide from the solution. When the hydroxide concentration becomes sufficiently high the soluble aluminate, Al(OH)4−, is formed.

Another common instance where precipitation occurs is when a metal cation interacts with an anionic ligand to form an electrically neutral complex. If the complex is hydrophobic, it will precipitate out of water. This occurs with the nickel ion Ni2+ and dimethylglyoxime, (dmgH2): in this case the lattice energy of the solid is not particularly large, but it greatly exceeds the energy of solvation of the molecule Ni(dmgH)2.

Minimization of Gibbs energy
At equilibrium, at a specified temperature and pressure, and with no external forces, the Gibbs free energy G is at a minimum:

 * $$dG= \sum_{j=1}^m \mu_j\,dN_j = 0$$

where μj is the chemical potential of molecular species j, and Nj is the amount of molecular species j. It may be expressed in terms of thermodynamic activity as:

 * $$\mu_j = \mu_j^{\ominus} + RT\ln{A_j}$$

where $$\mu_j^{\ominus}$$ is the chemical potential in the standard state, R is the gas constant T is the absolute temperature, and Aj is the activity.

For a closed system, no particles may enter or leave, although they may combine in various ways. The total number of atoms of each element will remain constant. This means that the minimization above must be subjected to the constraints:

 * $$\sum_{j=1}^m a_{ij}N_j=b_i^0$$

where aij is the number of atoms of element i in molecule j and b$0 i$ is the total number of atoms of element i, which is a constant, since the system is closed. If there are a total of k types of atoms in the system, then there will be k such equations. If ions are involved, an additional row is added to the aij matrix specifying the respective charge on each molecule which will sum to zero.

This is a standard problem in optimisation, known as constrained minimisation. The most common method of solving it is using the method of Lagrange multipliers (although other methods may be used).

Define:

 * $$\mathcal{G}= G + \sum_{i=1}^k\lambda_i\left(\sum_{j=1}^m a_{ij}N_j-b_i^0\right)=0$$

where the λi are the Lagrange multipliers, one for each element. This allows each of the Nj and λj to be treated independently, and it can be shown using the tools of multivariate calculus that the equilibrium condition is given by

 * $$0 = \frac{\partial \mathcal{G}}{\partial N_j} = \mu_j + \sum_{i=1}^k \lambda_i a_{ij} $$
 * $$0 = \frac{\partial \mathcal{G}}{\partial \lambda_i} = \sum_{j=1}^m a_{ij}N_j-b_i^0$$

(For proof see Lagrange multipliers.) This is a set of (m + k) equations in (m + k) unknowns (the Nj and the λi) and may, therefore, be solved for the equilibrium concentrations Nj as long as the chemical activities are known as functions of the concentrations at the given temperature and pressure. (In the ideal case, activities are proportional to concentrations.) (See Thermodynamic databases for pure substances.) Note that the second equation is just the initial constraints for minimization.

This method of calculating equilibrium chemical concentrations is useful for systems with a large number of different molecules. The use of k atomic element conservation equations for the mass constraint is straightforward, and replaces the use of the stoichiometric coefficient equations. The results are consistent with those specified by chemical equations. For example, if equilibrium is specified by a single chemical equation:,

 * $$\sum_{j=0}^m \nu_j R_j=0$$

where νj is the stoichiometric coefficient for the j th molecule (negative for reactants, positive for products) and Rj is the symbol for the j th molecule, a properly balanced equation will obey:

 * $$\sum_{j=1}^m a_{ij} \nu_j =0$$

Multiplying the first equilibrium condition by νj and using the above equation yields:

 * $$0 =\sum_{j=1}^m \nu_j \mu_j + \sum_{j=1}^m \sum_{i=1}^k \nu_j \lambda_i a_{ij} = \sum_{j=1}^m \nu_j \mu_j   $$

As above, defining ΔG

 * $$\Delta G=\sum_{j=1}^m \nu_j \mu_j = \sum_{j=1}^m \nu_j (\mu_j^{\ominus} + RT \ln(\{R_j\})) = \Delta G^{\ominus} + RT \ln\left(\prod_{j=1}^m \{R_j\}^{\nu_j}\right) = \Delta G^{\ominus} + RT \ln(K_c)$$

where Kc is the equilibrium constant, and ΔG will be zero at equilibrium.

Analogous procedures exist for the minimization of other thermodynamic potentials.

title: Chemical equilibrium


text:
Combination

In mathematics, a combination is a selection of items from a set that has distinct members, such that the order of selection does not matter (unlike permutations). For example, given three fruits, say an apple, an orange and a pear, there are three combinations of two that can be drawn from this set: an apple and a pear; an apple and an orange; or a pear and an orange. More formally, a k-combination of a set S is a subset of k distinct elements of S. So, two combinations are identical if and only if each combination has the same members. (The arrangement of the members in each set does not matter.) If the set has n elements, the number of k-combinations, denoted by $$C(n,k)$$ or $$C^n_k$$, is equal to the binomial coefficient

$$ \binom nk = \frac{n(n-1)\dotsb(n-k+1)}{k(k-1)\dotsb1},$$

which can be written using factorials as $$\textstyle\frac{n!}{k!(n-k)!}$$ whenever $$k\leq n$$, and which is zero when $$k>n$$. This formula can be derived from the fact that each k-combination of a set S of n members has $$k!$$ permutations so $$P^n_k = C^n_k \times k!$$ or $$C^n_k = P^n_k / k!$$. The set of all k-combinations of a set S is often denoted by $$\textstyle\binom Sk$$.

A combination is a combination of n things taken k at a time without repetition. To refer to combinations in which repetition is allowed, the terms k-combination with repetition, k-multiset, or k-selection, are often used. If, in the above example, it were possible to have two of any one kind of fruit there would be 3 more 2-selections: one with two apples, one with two oranges, and one with two pears.

Although the set of three fruits was small enough to write a complete list of combinations, this becomes impractical as the size of the set increases. For example, a poker hand can be described as a 5-combination (k = 5) of cards from a 52 card deck (n = 52). The 5 cards of the hand are all distinct, and the order of cards in the hand does not matter. There are 2,598,960 such combinations, and the chance of drawing any one hand at random is 1 / 2,598,960.

Number of k-combinations
The number of k-combinations from a given set S of n elements is often denoted in elementary combinatorics texts by $$C(n,k)$$, or by a variation such as $$C^n_k$$, $${}_nC_k$$, $${}^nC_k$$, $$C_{n,k}$$ or even $$C_n^k$$ (the last form is standard in French, Romanian, Russian, and Chinese texts.   The same number however occurs in many other mathematical contexts, where it is denoted by $$\tbinom nk$$ (often read as "n choose k"); notably it occurs as a coefficient in the binomial formula, hence its name binomial coefficient. One can define $$\tbinom nk$$ for all natural numbers k at once by the relation

$$(1 + X)^n = \sum_{k\geq0}\binom{n}{k} X^k,$$

from which it is clear that

$$\binom{n}{0} = \binom{n}{n} = 1,$$

and further

$$\binom{n}{k} = 0$$

for k > n.

To see that these coefficients count k-combinations from S, one can first consider a collection of n distinct variables Xs labeled by the elements s of S, and expand the product over all elements of S:

$$\prod_{s\in S}(1+X_s);$$

it has 2n distinct terms corresponding to all the subsets of S, each subset giving the product of the corresponding variables Xs. Now setting all of the Xs equal to the unlabeled variable X, so that the product becomes (1 + X)n, the term for each k-combination from S becomes Xk, so that the coefficient of that power in the result equals the number of such k-combinations.

Binomial coefficients can be computed explicitly in various ways. To get all of them for the expansions up to (1 + X)n, one can use (in addition to the basic cases already given) the recursion relation

$$\binom{n}{k} = \binom{n - 1}{k - 1} + \binom{n - 1}{k},$$

for 0 < k < n, which follows from (1 + X)n=(1 + X)n − 1(1 + X); this leads to the construction of Pascal's triangle.

For determining an individual binomial coefficient, it is more practical to use the formula

$$\binom nk = \frac{n(n-1)(n-2)\cdots(n-k+1)}{k!}.$$

The numerator gives the number of k-permutations of n, i.e., of sequences of k distinct elements of S, while the denominator gives the number of such k-permutations that give the same k-combination when the order is ignored.

When k exceeds n/2, the above formula contains factors common to the numerator and the denominator, and canceling them out gives the relation

$$ \binom nk = \binom n{n-k},$$

for 0 ≤ k ≤ n. This expresses a symmetry that is evident from the binomial formula, and can also be understood in terms of k-combinations by taking the complement of such a combination, which is an (n − k)-combination.

Finally there is a formula which exhibits this symmetry directly, and has the merit of being easy to remember:

$$ \binom nk = \frac{n!}{k!(n-k)!},$$

where n ! denotes the factorial of n. It is obtained from the previous formula by multiplying denominator and numerator by (n − k)!, so it is certainly computationally less efficient than that formula.

The last formula can be understood directly, by considering the n ! permutations of all the elements of S. Each such permutation gives a k-combination by selecting its first k elements. There are many duplicate selections: any combined permutation of the first k elements among each other, and of the final (n − k) elements among each other produces the same combination; this explains the division in the formula.

From the above formulas follow relations between adjacent numbers in Pascal's triangle in all three directions:

$$ \binom nk = \begin{cases} \binom n{k-1} \frac {n-k+1}k &\quad \text{if } k > 0 \\ \binom {n-1}k \frac n{n-k} &\quad \text{if } k < n \\ \binom {n-1}{k-1} \frac nk &\quad \text{if } n, k > 0 \end{cases}. $$

Together with the basic cases $$\tbinom n0=1=\tbinom nn$$, these allow successive computation of respectively all numbers of combinations from the same set (a row in Pascal's triangle), of k-combinations of sets of growing sizes, and of combinations with a complement of fixed size n − k.

Example of counting combinations
As a specific example, one can compute the number of five-card hands possible from a standard fifty-two card deck as:

$$ {52 \choose 5} = \frac{52\times51\times50\times49\times48}{5\times4\times3\times2\times1} = \frac{311{,}875{,}200}{120} = 2{,}598{,}960.$$

Alternatively one may use the formula in terms of factorials and cancel the factors in the numerator against parts of the factors in the denominator, after which only multiplication of the remaining factors is required: $$\begin{alignat}{2} {52 \choose 5} &= \frac{52!}{5!47!} \\[5pt] &= \frac{52\times51\times50\times49\times48\times\cancel{47!}}{5\times4\times3\times2\times\cancel{1}\times\cancel{47!}} \\[5pt] &= \frac{52\times51\times50\times49\times48}{5\times4\times3\times2} \\[5pt] &= \frac{(26\times\cancel{2})\times(17\times\cancel{3})\times(10\times\cancel{5})\times49\times(12\times\cancel{4})}{\cancel{5}\times\cancel{4}\times\cancel{3}\times\cancel{2}} \\[5pt] &= {26\times17\times10\times49\times12} \\[5pt] &= 2{,}598{,}960. \end{alignat}$$

Another alternative computation, equivalent to the first, is based on writing

$$ {n \choose k} = \frac { ( n - 0 ) }1 \times \frac { ( n - 1 ) }2 \times \frac { ( n - 2 ) }3 \times \cdots \times \frac { ( n - (k - 1) ) }k,$$

which gives

$$ {52 \choose 5} = \frac{52}1 \times \frac{51}2 \times \frac{50}3 \times \frac{49}4 \times \frac{48}5 = 2{,}598{,}960.$$

When evaluated in the following order, $52 ÷ 1 × 51 ÷ 2 × 50 ÷ 3 × 49 ÷ 4 × 48 ÷ 5$, this can be computed using only integer arithmetic. The reason is that when each division occurs, the intermediate result that is produced is itself a binomial coefficient, so no remainders ever occur.

Using the symmetric formula in terms of factorials without performing simplifications gives a rather extensive calculation:

$$ \begin{align} {52 \choose 5} &= \frac{n!}{k!(n-k)!} = \frac{52!}{5!(52-5)!} = \frac{52!}{5!47!} \\[6pt] &= \tfrac{80,658,175,170,943,878,571,660,636,856,403,766,975,289,505,440,883,277,824,000,000,000,000}{120\times258,623,241,511,168,180,642,964,355,153,611,979,969,197,632,389,120,000,000,000} \\[6pt] &= 2{,}598{,}960. \end{align}$$

Enumerating k-combinations
One can enumerate all k-combinations of a given set S of n elements in some fixed order, which establishes a bijection from an interval of $$\tbinom nk$$ integers with the set of those k-combinations. Assuming S is itself ordered, for instance S = { 1, 2, ..., n }, there are two natural possibilities for ordering its k-combinations: by comparing their smallest elements first (as in the illustrations above) or by comparing their largest elements first. The latter option has the advantage that adding a new largest element to S will not change the initial part of the enumeration, but just add the new k-combinations of the larger set after the previous ones. Repeating this process, the enumeration can be extended indefinitely with k-combinations of ever larger sets. If moreover the intervals of the integers are taken to start at 0, then the k-combination at a given place i in the enumeration can be computed easily from i, and the bijection so obtained is known as the combinatorial number system. It is also known as "rank"/"ranking" and "unranking" in computational mathematics.

There are many ways to enumerate k combinations. One way is to track k index numbers of the elements selected, starting with {0 .. k−1} (zero-based) or {1 .. k} (one-based) as the first allowed k-combination. Then, repeatedly move to the next allowed k-combination by incrementing the smallest index number for which this would not create two equal index numbers, at the same time resetting all smaller index numbers to their initial values.

Number of combinations with repetition
A k-combination with repetitions, or k-multicombination, or multisubset of size k from a set S of size n is given by a set of k not necessarily distinct elements of S, where order is not taken into account: two sequences define the same multiset if one can be obtained from the other by permuting the terms. In other words, it is a sample of k elements from a set of n elements allowing for duplicates (i.e., with replacement) but disregarding different orderings (e.g. {2,1,2} = {1,2,2}). Associate an index to each element of S and think of the elements of S as types of objects, then we can let $$x_i$$ denote the number of elements of type i in a multisubset. The number of multisubsets of size k is then the number of nonnegative integer (so allowing zero) solutions of the Diophantine equation:

$$x_1 + x_2 + \ldots + x_n = k.$$

If S has n elements, the number of such k-multisubsets is denoted by

$$\left(\!\!\binom{n}{k}\!\!\right),$$

a notation that is analogous to the binomial coefficient which counts k-subsets. This expression, n multichoose k, can also be given in terms of binomial coefficients:

$$\left(\!\!\binom{n}{k}\!\!\right)=\binom{n+k-1}{k}.$$

This relationship can be easily proved using a representation known as stars and bars.

A solution of the above Diophantine equation can be represented by $$x_1$$ stars, a separator (a bar), then $$x_2$$ more stars, another separator, and so on. The total number of stars in this representation is k and the number of bars is n - 1 (since a separation into n parts needs n-1 separators). Thus, a string of k + n - 1 (or n + k - 1) symbols (stars and bars) corresponds to a solution if there are k stars in the string. Any solution can be represented by choosing k out of positions to place stars and filling the remaining positions with bars. For example, the solution $$x_1 = 3, x_2 = 2, x_3 = 0, x_4 = 5$$ of the equation $$ x_1 + x_2 + x_3 + x_4 = 10$$ (n = 4 and k = 10) can be represented by

$$\bigstar \bigstar \bigstar | \bigstar \bigstar | | \bigstar \bigstar \bigstar \bigstar \bigstar.$$

The number of such strings is the number of ways to place 10 stars in 13 positions, $\binom{13}{10} = \binom{13}{3} = 286,$ which is the number of 10-multisubsets of a set with 4 elements.

As with binomial coefficients, there are several relationships between these multichoose expressions. For example, for $$ n \ge 1, k \ge 0$$,

$$\left(\!\!\binom{n}{k}\!\!\right)=\left(\!\!\binom{k+1}{n-1}\!\!\right).$$ This identity follows from interchanging the stars and bars in the above representation.

Example of counting multisubsets
For example, if you have four types of donuts (n = 4) on a menu to choose from and you want three donuts (k = 3), the number of ways to choose the donuts with repetition can be calculated as

$$\left(\!\!\binom{4}{3}\!\!\right) = \binom{4+3-1}3 = \binom{6}{3} = \frac{6 \times 5 \times 4}{3 \times 2 \times 1} = 20.$$

This result can be verified by listing all the 3-multisubsets of the set S = {1,2,3,4}. This is displayed in the following table. The second column lists the donuts you actually chose, the third column shows the nonnegative integer solutions $$[x_1,x_2,x_3,x_4]$$ of the equation $$x_1 + x_2 + x_3 + x_4 = 3$$ and the last column gives the stars and bars representation of the solutions.

Number of k-combinations for all k
The number of k-combinations for all k is the number of subsets of a set of n elements. There are several ways to see that this number is 2n. In terms of combinations, $\sum_{0\leq{k}\leq{n}}\binom n k = 2^n$, which is the sum of the nth row (counting from 0) of the binomial coefficients in Pascal's triangle. These combinations (subsets) are enumerated by the 1 digits of the set of base 2 numbers counting from 0 to 2n − 1, where each digit position is an item from the set of n.

Given 3 cards numbered 1 to 3, there are 8 distinct combinations (subsets), including the empty set:

$$| \{ \{\} ;  \{1\}  ;  \{2\}  ;  \{1, 2\} ; \{3\}  ;  \{1, 3\}  ;  \{2, 3\}  ;  \{1, 2, 3\} \}| = 2^3 = 8$$

Representing these subsets (in the same order) as base 2 numerals:

 * 0 – 000
 * 1 – 001
 * 2 – 010
 * 3 – 011
 * 4 – 100
 * 5 – 101
 * 6 – 110
 * 7 – 111

Probability: sampling a random combination
There are various algorithms to pick out a random combination from a given set or list. Rejection sampling is extremely slow for large sample sizes. One way to select a k-combination efficiently from a population of size n is to iterate across each element of the population, and at each step pick that element with a dynamically changing probability of $\frac{k-\#\text{samples chosen}}{n- \#\text{samples visited}}$ (see Reservoir sampling). Another is to pick a random non-negative integer less than $$\textstyle\binom nk$$ and convert it into a combination using the combinatorial number system.

Number of ways to put objects into bins
A combination can also be thought of as a selection of two sets of items: those that go into the chosen bin and those that go into the unchosen bin. This can be generalized to any number of bins with the constraint that every item must go to exactly one bin. The number of ways to put objects into bins is given by the multinomial coefficient

$$ {n \choose k_1, k_2, \ldots, k_m} = \frac{n!}{k_1!\, k_2! \cdots k_m!},$$

where n is the number of items, m is the number of bins, and $$k_i$$ is the number of items that go into bin i.

One way to see why this equation holds is to first number the objects arbitrarily from 1 to n and put the objects with numbers $$1, 2, \ldots, k_1$$ into the first bin in order, the objects with numbers $$k_1+1, k_1+2, \ldots, k_2$$ into the second bin in order, and so on. There are $$n!$$ distinct numberings, but many of them are equivalent, because only the set of items in a bin matters, not their order in it. Every combined permutation of each bins' contents produces an equivalent way of putting items into bins. As a result, every equivalence class consists of $$k_1!\, k_2! \cdots k_m!$$ distinct numberings, and the number of equivalence classes is $$\textstyle\frac{n!}{k_1!\, k_2! \cdots k_m!}$$.

The binomial coefficient is the special case where k items go into the chosen bin and the remaining $$n-k$$ items go into the unchosen bin:

$$ \binom nk = {n \choose k, n-k} = \frac{n!}{k!(n-k)!}. $$

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

title: Combination


text:
Software

Software consists of computer programs that instruct the execution of a computer.

Building on previous innovations in mathematics and technology, software was created for the programmable digital computers that emerged in the late 1940s and was necessary to realize their usefulness. The first software was tied closely to the underlying computer hardware, but over time, the lower layers of the system have become more standardized, and software has become increasingly portable between different systems and abstracted from the underlying machine code. Operating systems manage the hardware resources and mediate between different applications that accomplish tasks for the user. Programming languages are the format in which software is written, and must be both human-readable and capable of being translated into unambiguous instructions for computer hardware. Compilers or interpreters are needed to link a program with other code that it relies on and convert the software into machine code that can be executed on the hardware. Programs are combined with each other and with external input to be capable of accomplishing a complex task.

Software development's central task is programming and maintaining a project's source code, but the term also covers conceiving the project, evaluating its feasibility, analyzing the business requirements, software design, and release. Software quality assurance, including code review and testing, is an essential part of the process, as delivering quality code lowers the cost of reliability failures, cyberattacks enabled by security vulnerabilities, and maintenance costs. Maintenance typically consumes 75 percent or more of the software's lifetime engineering budget. Source code is protected by copyright law, which vests the owner with the exclusive right to copy the code. Software has become ubiquitous in everyday life in developed countries. In many cases, software augments the functionality of pre-existing technologies, but it has also enabled the creation of entirely new technologies such as the Internet, video games, social media, mobile phones, and GPS.

Definition
Software can be defined more narrowly as the instructions executed by the computer hardware, or more broadly including other concepts, tools, and methods needed to make an executable system on computer hardware, such as design documents, specifications, and testing suites. An individual program or source code file consists of unambiguous instructions and algorithms. Programs are combined with each other and with external input to be capable of accomplishing a complex task. Tools such as compilers, assemblers, flowcharts, design tools, simulators, and architectural diagrams—some of which are also software—are essential to the design and execution of most computing systems. Although software is intangible, software makes instructions for computer hardware to produce visible and tangible effects.

History

A host of earlier inventions were necessary for the creation of software, including mathematics—especially binary and decimal number systems, and zero—alphabets, writing, mechanical calculators, boolean algebra, transistors, integrated circuits, and plastics. Software could not exist without digital computers, as it was created specifically for these devices and was necessary to realize their usefulness.

The first programmable computers, which appeared at the end of the 1940s, were programmed in machine language (simple instructions that could be directly executed by the processor). Machine language was difficult to debug and was not portable between different computer systems. Initially, hardware resources were scarce and expensive, while human resources were cheaper. As programs grew more complex, programmer productivity became a bottleneck. This led to the introduction of high-level programming languages in the mid-1950s. These languages abstracted away the details of the hardware, instead being designed to express algorithms that could be understood more easily by humans. As instructions are distinct from the underlying computer hardware, software is therefore relatively recent, dating to these early high-level programming languages such as Fortran, Lisp, and Cobol. The first use of the word software is credited to mathematician John Wilder Tukey in 1958. As this first definition of software was negative (elements of a computer that were not “tubes, transistors, wires, tapes and the like.”), it left open for a broad understanding of the concept of software, as Historian of Computing Nathan Ensmenger posits. For historians, software is a sociotechnical system, which means "a system in which machines, people, and processes are inextricably interconnected and interdependent", in Ensmenger's words. Historian of Computing Thomas Haigh insists on the idea of circulation and argues “software always involves packaging disparate elements such as computer code, practices, algorithms, tacit knowledge, and intellectual property rights into an artifact suitable for dissemination”.

The first software was tied closely to the underlying hardware and, consequently, was not portable to other systems. As it has evolved, newer software can be built and run on a wide variety of platforms. Much of the increase in portability can be attributed to the standardization of lower-level aspects of the system, such as networking, operating systems, and databases. Because there are only a relatively few operating systems, TCP and IP are used for virtually all networking, and SQL is used for many database queries, application software can run more easily over a wide variety of hardware. Increasing the number of layers of abstraction in the system is a related development: both in programming languages where it enables better structure and increased modularity, as well as enabling virtualization of system resources. As a result of the increase in stability and abstraction, software has become increasingly complex and can solve more problems. Both industry and academia have had a strong influence on the development of different aspects of software.

Types
There are two main types of software:
 * Operating systems are "the layer of software that manages a computer's resources for its users and their applications". There are three main purposes that an operating system fulfills:
 * Allocating resources between different applications, deciding when they will receive central processing unit (CPU) time or space in memory.
 * Providing an interface that abstracts the details of accessing hardware details (like physical memory) to make things easier for programmers.
 * Offering common services, such as an interface for accessing network and disk devices. This enables an application to be run on different hardware without needing to be rewritten.
 * Application software runs on top of the operating system and uses the computer's resources to perform a task. There are many different types of application software because the range of tasks that can be performed with modern computers is so large. Applications account for most software and require the environment provided by an operating system, and often other applications, in order to function.

Software can also be categorized by how it is deployed. Traditional applications are purchased with a perpetual license for a specific version of the software, downloaded, and run on hardware belonging to the purchaser. The rise of the Internet and cloud computing enabled a new model, software as a service (SaaS), in which the provider hosts the software (usually built on top of rented infrastructure or platforms) and provides the use of the software to customers, often in exchange for a subscription fee. By 2023, SaaS products—which are usually delivered via a web application—had become the primary method that companies deliver applications.

Software development and maintenance

Software companies aim to deliver a high-quality product on time and under budget. A challenge is that software development effort estimation is often inaccurate. Software development begins by conceiving the project, evaluating its feasibility, analyzing the business requirements, and making a software design. Most software projects speed up their development by reusing or incorporating existing software, either in the form of commercial off-the-shelf (COTS) or open-source software. Software quality assurance is typically a combination of manual code review by other engineers and automated software testing. Due to time constraints, testing cannot cover all aspects of the software's intended functionality, so developers often focus on the most critical functionality. Formal methods are used in some safety-critical systems to prove the correctness of code, while user acceptance testing helps to ensure that the product meets customer expectations. There are a variety of software development methodologies, which vary from completing all steps in order to concurrent and iterative models. Software development is driven by requirements taken from prospective users, as opposed to maintenance, which is driven by events such as a change request.

Frequently, software is released in an incomplete state when the development team runs out of time or funding. Despite testing and quality assurance, virtually all software contains bugs where the system does not work as intended. Post-release software maintenance is necessary to remediate these bugs when they are found and keep the software working as the environment changes over time. New features are often added after the release. Over time, the level of maintenance becomes increasingly restricted before being cut off entirely when the product is withdrawn from the market. As software ages, it becomes known as legacy software and can remain in use for decades, even if there is no one left who knows how to fix it. Over the lifetime of the product, software maintenance is estimated to comprise 75 percent or more of the total development cost.

Completing a software project involves various forms of expertise, not just in software programmers but also testing, documentation writing, project management, graphic design, user experience, user support, marketing, and fundraising.

Quality and security
Software quality is defined as meeting the stated requirements as well as customer expectations. Quality is an overarching term that can refer to a code's correct and efficient behavior, its reusability and portability, or the ease of modification. It is usually more cost-effective to build quality into the product from the beginning rather than try to add it later in the development process. Higher quality code will reduce lifetime cost to both suppliers and customers as it is more reliable and easier to maintain. Software failures in safety-critical systems can be very serious including death. By some estimates, the cost of poor quality software can be as high as 20 to 40 percent of sales. Despite developers' goal of delivering a product that works entirely as intended, virtually all software contains bugs.

The rise of the Internet also greatly increased the need for computer security as it enabled malicious actors to conduct cyberattacks remotely. If a bug creates a security risk, it is called a vulnerability. Software patches are often released to fix identified vulnerabilities, but those that remain unknown (zero days) as well as those that have not been patched are still liable for exploitation. Vulnerabilities vary in their ability to be exploited by malicious actors, and the actual risk is dependent on the nature of the vulnerability as well as the value of the surrounding system. Although some vulnerabilities can only be used for denial of service attacks that compromise a system's availability, others allow the attacker to inject and run their own code (called malware), without the user being aware of it. To thwart cyberattacks, all software in the system must be designed to withstand and recover from external attack. Despite efforts to ensure security, a significant fraction of computers are infected with malware.

Programming languages
Programming languages are the format in which software is written. Since the 1950s, thousands of different programming languages have been invented; some have been in use for decades, while others have fallen into disuse. Some definitions classify machine code—the exact instructions directly implemented by the hardware—and assembly language—a more human-readable alternative to machine code whose statements can be translated one-to-one into machine code—as programming languages. Programs written in the high-level programming languages used to create software share a few main characteristics: knowledge of machine code is not necessary to write them, they can be ported to other computer systems, and they are more concise and human-readable than machine code. They must be both human-readable and capable of being translated into unambiguous instructions for computer hardware.

Compilation, interpretation, and execution
The invention of high-level programming languages was simultaneous with the compilers needed to translate them automatically into machine code. Most programs do not contain all the resources needed to run them and rely on external libraries. Part of the compiler's function is to link these files in such a way that the program can be executed by the hardware. Once compiled, the program can be saved as an object file and the loader (part of the operating system) can take this saved file and execute it as a process on the computer hardware. Some programming languages use an interpreter instead of a compiler. An interpreter converts the program into machine code at run time, which makes them 10 to 100 times slower than compiled programming languages.

Liability
Software is often released with the knowledge that it is incomplete or contains bugs. Purchasers knowingly buy it in this state, which has led to a legal regime where liability for software products is significantly curtailed compared to other products.

Licenses
Source code is protected by copyright law that vests the owner with the exclusive right to copy the code. The underlying ideas or algorithms are not protected by copyright law, but are often treated as a trade secret and concealed by such methods as non-disclosure agreements. Software copyright has been recognized since the mid-1970s and is vested in the company that makes the software, not the employees or contractors who wrote it. The use of most software is governed by an agreement (software license) between the copyright holder and the user. Proprietary software is usually sold under a restrictive license that limits copying and reuse (often enforced with tools such as digital rights management (DRM)). Open-source licenses, in contrast, allow free use and redistribution of software with few conditions. Most open-source licenses used for software require that modifications be released under the same license, which can create complications when open-source software is reused in proprietary projects.

Patents
Patents give an inventor an exclusive, time-limited license for a novel product or process. Ideas about what software could accomplish are not protected by law and concrete implementations are instead covered by copyright law. In some countries, a requirement for the claimed invention to have an effect on the physical world may also be part of the requirements for a software patent to be held valid. Software patents have been historically controversial. Before the 1998 case State Street Bank & Trust Co. v. Signature Financial Group, Inc., software patents were generally not recognized in the United States. In that case, the Supreme Court decided that business processes could be patented. Patent applications are complex and costly, and lawsuits involving patents can drive up the cost of products. Unlike copyrights, patents generally only apply in the jurisdiction where they were issued.

Impact
Engineer Capers Jones writes that "computers and software are making profound changes to every aspect of human life: education, work, warfare, entertainment, medicine, law, and everything else". It has become ubiquitous in everyday life in developed countries. In many cases, software augments the functionality of existing technologies such as household appliances and elevators. Software also spawned entirely new technologies such as the Internet, video games, mobile phones, and GPS. New methods of communication, including email, forums, blogs, microblogging, wikis, and social media, were enabled by the Internet. Massive amounts of knowledge exceeding any paper-based library are now available with a quick web search. Most creative professionals have switched to software-based tools such as computer-aided design, 3D modeling, digital image editing, and computer animation. Almost every complex device is controlled by software.

title: Software


text:
Computer programming

Computer programming or coding is the composition of sequences of instructions, called programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of procedures, by writing code in one or more programming languages. Programmers typically use high-level programming languages that are more easily intelligible to humans than machine code, which is directly executed by the central processing unit. Proficient programming usually requires expertise in several different subjects, including knowledge of the application domain, details of programming languages and generic code libraries, specialized algorithms, and formal logic.

Auxiliary tasks accompanying and related to programming include analyzing requirements, testing, debugging (investigating and fixing problems), implementation of build systems, and management of derived artifacts, such as programs' machine code. While these are sometimes considered programming, often the term software development is used for this larger overall process – with the terms programming, implementation, and coding reserved for the writing and editing of code per se. Sometimes software development is known as software engineering, especially when it employs formal methods or follows an engineering design process.

History

Programmable devices have existed for centuries. As early as the 9th century, a programmable music sequencer was invented by the Persian Banu Musa brothers, who described an automated mechanical flute player in the Book of Ingenious Devices. In 1206, the Arab engineer Al-Jazari invented a programmable drum machine where a musical mechanical automaton could be made to play different rhythms and drum patterns, via pegs and cams. In 1801, the Jacquard loom could produce entirely different weaves by changing the "program" – a series of pasteboard cards with holes punched in them.

Code-breaking algorithms have also existed for centuries. In the 9th century, the Arab mathematician Al-Kindi described a cryptographic algorithm for deciphering encrypted code, in A Manuscript on Deciphering Cryptographic Messages. He gave the first description of cryptanalysis by frequency analysis, the earliest code-breaking algorithm.

The first computer program is generally dated to 1843 when mathematician Ada Lovelace published an algorithm to calculate a sequence of Bernoulli numbers, intended to be carried out by Charles Babbage's Analytical Engine. However, Charles Babbage himself, wrote his first program for the AE in 1837.

In the 1880s, Herman Hollerith invented the concept of storing data in machine-readable form. Later a control panel (plug board) added to his 1906 Type I Tabulator allowed it to be programmed for different jobs, and by the late 1940s, unit record equipment such as the IBM 602 and IBM 604, were programmed by control panels in a similar way, as were the first electronic computers. However, with the concept of the stored-program computer introduced in 1949, both programs and data were stored and manipulated in the same way in computer memory.

Machine language
Machine code was the language of early programs, written in the instruction set of the particular machine, often in binary notation. Assembly languages were soon developed that let the programmer specify instructions in a text format (e.g., ADD X, TOTAL), with abbreviations for each operation code and meaningful names for specifying addresses. However, because an assembly language is little more than a different notation for a machine language, two machines with different instruction sets also have different assembly languages.

Compiler languages
High-level languages made the process of developing a program simpler and more understandable, and less bound to the underlying hardware. The first compiler related tool, the A-0 System, was developed in 1952 by Grace Hopper, who also coined the term 'compiler'. FORTRAN, the first widely used high-level language to have a functional implementation, came out in 1957, and many other languages were soon developed—in particular, COBOL aimed at commercial data processing, and Lisp for computer research.

These compiled languages allow the programmer to write programs in terms that are syntactically richer, and more capable of abstracting the code, making it easy to target varying machine instruction sets via compilation declarations and heuristics. Compilers harnessed the power of computers to make programming easier by allowing programmers to specify calculations by entering a formula using infix notation.

Source code entry
Programs were mostly entered using punched cards or paper tape. By the late 1960s, data storage devices and computer terminals became inexpensive enough that programs could be created by typing directly into the computers. Text editors were also developed that allowed changes and corrections to be made much more easily than with punched cards.

Quality requirements
Whatever the approach to development may be, the final program must satisfy some fundamental properties. The following properties are among the most important: Using automated tests and fitness functions can help to maintain some of the aforementioned attributes.
 * Reliability: how often the results of a program are correct. This depends on conceptual correctness of algorithms and minimization of programming mistakes, such as mistakes in resource management (e.g., buffer overflows and race conditions) and logic errors (such as division by zero or off-by-one errors).
 * Robustness: how well a program anticipates problems due to errors (not bugs). This includes situations such as incorrect, inappropriate or corrupt data, unavailability of needed resources such as memory, operating system services, and network connections, user error, and unexpected power outages.
 * Usability: the ergonomics of a program: the ease with which a person can use the program for its intended purpose or in some cases even unanticipated purposes. Such issues can make or break its success even regardless of other issues. This involves a wide range of textual, graphical, and sometimes hardware elements that improve the clarity, intuitiveness, cohesiveness, and completeness of a program's user interface.
 * Portability: the range of computer hardware and operating system platforms on which the source code of a program can be compiled/interpreted and run. This depends on differences in the programming facilities provided by the different platforms, including hardware and operating system resources, expected behavior of the hardware and operating system, and availability of platform-specific compilers (and sometimes libraries) for the language of the source code.
 * Maintainability: the ease with which a program can be modified by its present or future developers in order to make improvements or to customize, fix bugs and security holes, or adapt it to new environments. Good practices during initial development make the difference in this regard. This quality may not be directly apparent to the end user but it can significantly affect the fate of a program over the long term.
 * Efficiency/performance: Measure of system resources a program consumes (processor time, memory space, slow devices such as disks, network bandwidth and to some extent even user interaction): the less, the better. This also includes careful management of resources, for example cleaning up temporary files and eliminating memory leaks. This is often discussed under the shadow of a chosen programming language. Although the language certainly affects performance, even slower languages, such as Python, can execute programs instantly from a human perspective. Speed, resource usage, and performance are important for programs that bottleneck the system, but efficient use of programmer time is also important and is related to cost: more hardware may be cheaper.

Readability of source code
In computer programming, readability refers to the ease with which a human reader can comprehend the purpose, control flow, and operation of source code. It affects the aspects of quality above, including portability, usability and most importantly maintainability.

Readability is important because programmers spend the majority of their time reading, trying to understand, reusing, and modifying existing source code, rather than writing new source code. Unreadable code often leads to bugs, inefficiencies, and duplicated code. A study found that a few simple readability transformations made code shorter and drastically reduced the time to understand it.

Following a consistent programming style often helps readability. However, readability is more than just programming style. Many factors, having little or nothing to do with the ability of the computer to efficiently compile and execute the code, contribute to readability. Some of these factors include:
 * Different indent styles (whitespace)
 * Comments
 * Decomposition
 * Naming conventions for objects (such as variables, classes, functions, procedures, etc.)

The presentation aspects of this (such as indents, line breaks, color highlighting, and so on) are often handled by the source code editor, but the content aspects reflect the programmer's talent and skills.

Various visual programming languages have also been developed with the intent to resolve readability concerns by adopting non-traditional approaches to code structure and display. Integrated development environments (IDEs) aim to integrate all such help. Techniques like Code refactoring can enhance readability.

Algorithmic complexity
The academic field and the engineering practice of computer programming are both largely concerned with discovering and implementing the most efficient algorithms for a given class of problems. For this purpose, algorithms are classified into orders using the so-called Big O notation, which expresses resource use, such as execution time or memory consumption, in terms of the size of an input. Expert programmers are familiar with a variety of well-established algorithms and their respective complexities and use this knowledge to choose algorithms that are best suited to the circumstances.

Methodologies
The first step in most formal software development processes is requirements analysis, followed by testing to determine value modeling, implementation, and failure elimination (debugging). There exist a lot of different approaches for each of those tasks. One approach popular for requirements analysis is Use Case analysis. Many programmers use forms of Agile software development where the various stages of formal software development are more integrated together into short cycles that take a few weeks rather than years. There are many approaches to the Software development process.

Popular modeling techniques include Object-Oriented Analysis and Design (OOAD) and Model-Driven Architecture (MDA). The Unified Modeling Language (UML) is a notation used for both the OOAD and MDA.

A similar technique used for database design is Entity-Relationship Modeling (ER Modeling).

Implementation techniques include imperative languages (object-oriented or procedural), functional languages, and logic languages.

Measuring language usage
It is very difficult to determine what are the most popular modern programming languages. Methods of measuring programming language popularity include: counting the number of job advertisements that mention the language, the number of books sold and courses teaching the language (this overestimates the importance of newer languages), and estimates of the number of existing lines of code written in the language (this underestimates the number of users of business languages such as COBOL).

Some languages are very popular for particular kinds of applications, while some languages are regularly used to write many different kinds of applications. For example, COBOL is still strong in corporate data centers often on large mainframe computers, Fortran in engineering applications, scripting languages in Web development, and C in embedded software. Many applications use a mix of several languages in their construction and use. New languages are generally designed around the syntax of a prior language with new functionality added, (for example C++ adds object-orientation to C, and Java adds memory management and bytecode to C++, but as a result, loses efficiency and the ability for low-level manipulation).

Debugging
Debugging is a very important task in the software development process since having defects in a program can have significant consequences for its users. Some languages are more prone to some kinds of faults because their specification does not require compilers to perform as much checking as other languages. Use of a static code analysis tool can help detect some possible problems. Normally the first step in debugging is to attempt to reproduce the problem. This can be a non-trivial task, for example as with parallel processes or some unusual software bugs. Also, specific user environment and usage history can make it difficult to reproduce the problem.

After the bug is reproduced, the input of the program may need to be simplified to make it easier to debug. For example, when a bug in a compiler can make it crash when parsing some large source file, a simplification of the test case that results in only few lines from the original source file can be sufficient to reproduce the same crash. Trial-and-error/divide-and-conquer is needed: the programmer will try to remove some parts of the original test case and check if the problem still exists. When debugging the problem in a GUI, the programmer can try to skip some user interaction from the original problem description and check if the remaining actions are sufficient for bugs to appear. Scripting and breakpointing are also part of this process.

Debugging is often done with IDEs. Standalone debuggers like GDB are also used, and these often provide less of a visual environment, usually using a command line. Some text editors such as Emacs allow GDB to be invoked through them, to provide a visual environment.

Programming languages
Different programming languages support different styles of programming (called programming paradigms). The choice of language used is subject to many considerations, such as company policy, suitability to task, availability of third-party packages, or individual preference. Ideally, the programming language best suited for the task at hand will be selected. Trade-offs from this ideal involve finding enough programmers who know the language to build a team, the availability of compilers for that language, and the efficiency with which programs written in a given language execute. Languages form an approximate spectrum from "low-level" to "high-level"; "low-level" languages are typically more machine-oriented and faster to execute, whereas "high-level" languages are more abstract and easier to use but execute less quickly. It is usually easier to code in "high-level" languages than in "low-level" ones. Programming languages are essential for software development. They are the building blocks for all software, from the simplest applications to the most sophisticated ones.

Allen Downey, in his book How To Think Like A Computer Scientist, writes:

 * The details look different in different languages, but a few basic instructions appear in just about every language:
 * Input: Gather data from the keyboard, a file, or some other device.
 * Output: Display data on the screen or send data to a file or other device.
 * Arithmetic: Perform basic arithmetical operations like addition and multiplication.
 * Conditional Execution: Check for certain conditions and execute the appropriate sequence of statements.
 * Repetition: Perform some action repeatedly, usually with some variation.

Many computer languages provide a mechanism to call functions provided by shared libraries. Provided the functions in a library follow the appropriate run-time conventions (e.g., method of passing arguments), then these functions may be written in any other language.

Programmers
Computer programmers are those who write computer software. Their jobs usually involve:

Although programming has been presented in the media as a somewhat mathematical subject, some research shows that good programmers have strong skills in natural human languages, and that learning to code is similar to learning a foreign language.
 * Prototyping
 * Coding
 * Debugging
 * Documentation
 * Integration
 * Maintenance
 * Requirements analysis
 * Software architecture
 * Software testing
 * Specification

title: Computer programming


text:
On the Consolation of Philosophy

On the Consolation of Philosophy (De consolatione philosophiae), often titled as The Consolation of Philosophy or simply the Consolation, is a philosophical work by the Roman philosopher Boethius. Written in 523 while he was imprisoned and awaiting execution by the Ostrogothic King Theodoric, it is often described as the last great Western work of the Classical Period. Boethius' Consolation heavily influenced the philosophy of late antiquity, as well as Medieval and early Renaissance Christianity.

Description
On the Consolation of Philosophy was written in AD 523 during a one-year imprisonment Boethius served while awaiting trial—and eventual execution—for the alleged crime of treason under the Ostrogothic King Theodoric the Great. Boethius was at the very heights of power in Rome, holding the prestigious office of magister officiorum, and was brought down by treachery. This experience inspired the text, which reflects on how evil can exist in a world governed by God (the problem of theodicy), and how happiness is still attainable amidst fickle fortune, while also considering the nature of happiness and God. In 1891, the academic Hugh Fraser Stewart described the work as "by far the most interesting example of prison literature the world has ever seen."

Boethius writes the book as a conversation between himself and a female personification of philosophy, referred to as "Lady Philosophy". Philosophy consoles Boethius by discussing the transitory nature of wealth, fame, and power ("no man can ever truly be secure until he has been forsaken by Fortune"), and the ultimate superiority of things of the mind, which she calls the "one true good". She contends that happiness comes from within, and that virtue is all that one truly has because it is not imperiled by the vicissitudes of fortune.

Boethius engages with the nature of predestination and free will, the problem of evil and the "problem of desert", human nature, virtue, and justice. He speaks about the nature of free will and determinism when he asks whether God knows and sees all, or does man have free will. On human nature, Boethius says that humans are essentially good, and only when they give in to "wickedness" do they "sink to the level of being an animal." On justice, he says criminals are not to be abused, but rather treated with sympathy and respect, using the analogy of doctor and patient to illustrate the ideal relationship between prosecutor and criminal.

Outline
On the Consolation of Philosophy is laid out as follows:
 * Book I: Boethius laments his imprisonment before he is visited by Philosophy, personified as a woman.
 * Book II: Philosophy illustrates the capricious nature of Fate by discussing the "wheel of Fortune"; she further argues that true happiness lies in the pursuit of wisdom.
 * Book III: Building on the ideas laid out in the previous book, Philosophy explains how wisdom has a divine source; she also demonstrates how many earthly goods (e.g., wealth, beauty) are fleeting at best.
 * Book IV: Philosophy and Boethius discuss the nature of good and evil, with Philosophy offering several explanations concerned with evil events and why the wicked can never attain true happiness.
 * Book V: Boethius asks Philosophy about the role Chance plays in the order of everything. Philosophy argues that Chance is guided by Providence. Boethius then asks Philosophy about the compatibility of an omniscient God and free will.

Interpretation
In the Consolation, Boethius answered religious questions without reference to Christianity, relying solely on natural philosophy and the Classical Greek tradition. He believed in the correspondence between faith and reason. The truths found in Christianity would be no different from the truths found in philosophy. In the words of Henry Chadwick, "If the Consolation contains nothing distinctively Christian, it is also relevant that it contains nothing specifically pagan either...[it] is a work written by a Platonist who is also a Christian."

Boethius repeats the Macrobius model of the Earth in the center of a spherical cosmos.

The philosophical message of the book fits well with the religious piety of the Middle Ages. Boethius encouraged readers not to pursue worldly goods such as money and power, but to seek internalized virtues. Evil had a purpose, to provide a lesson to help change for good; while suffering from evil was seen as virtuous. Because God ruled the universe through Love, prayer to God and the application of Love would lead to true happiness. The Middle Ages, with their vivid sense of an overruling fate, found in Boethius an interpretation of life closely akin to the spirit of Christianity. The Consolation stands, by its note of fatalism and its affinities with the Christian doctrine of humility, midway between the pagan philosophy of Seneca the Younger and the later Christian philosophy of consolation represented by Thomas à Kempis.

The book is heavily influenced by Plato and his dialogues (as was Boethius himself). Its popularity can in part be explained by its Neoplatonic and Christian ethical messages, although current scholarly research is still far from clear exactly why and how the work became so vastly popular in the Middle Ages.

Influence

From the Carolingian epoch to the end of the Middle Ages and beyond, The Consolation of Philosophy was one of the most popular and influential philosophical works, read by statesmen, poets, historians, philosophers, and theologians. It is through Boethius that much of the thought of the Classical period was made available to the Western Medieval world. It has often been said Boethius was the "last of the Romans and the first of the Scholastics".

Translations into the vernacular were done by famous notables, including King Alfred (Old English), Jean de Meun (Old French), Geoffrey Chaucer (Middle English), Queen Elizabeth I (Early Modern English) and Notker Labeo (Old High German). Boethius's Consolation of Philosophy was translated into Italian by Alberto della Piagentina (1332), Anselmo Tanso (Milan, 1520), Lodovico Domenichi (Florence, 1550), Benedetto Varchi (Florence, 1551), Cosimo Bartoli (Florence, 1551) and Tommaso Tamburini (Palermo, 1657).

Found within the Consolation are themes that have echoed throughout the Western canon: the female figure of wisdom that informs Dante, the ascent through the layered universe that is shared with Milton, the reconciliation of opposing forces that find their way into Chaucer in The Knight's Tale, and the Wheel of Fortune so popular throughout the Middle Ages.

Citations from it occur frequently in Dante's Divina Commedia. Of Boethius, Dante remarked: "The blessed soul who exposes the deceptive world to anyone who gives ear to him."

Boethian influence can be found nearly everywhere in Geoffrey Chaucer's poetry, e.g. in Troilus and Criseyde, The Knight's Tale, The Clerk's Tale, The Franklin's Tale, The Parson's Tale and The Tale of Melibee, in the character of Lady Nature in The Parliament of Fowls and some of the shorter poems, such as Truth, The Former Age and Lak of Stedfastnesse. Chaucer translated the work in his Boece.

The Italian composer Luigi Dallapiccola used some of the text in his choral work Canti di prigionia (1938). The Australian composer Peter Sculthorpe quoted parts of it in his opera or music theatre work Rites of Passage (1972–73), which was commissioned for the opening of the Sydney Opera House but was not ready in time.

Tom Shippey in The Road to Middle-earth says how "Boethian" much of the treatment of evil is in Tolkien's The Lord of the Rings. Shippey says that Tolkien knew well the translation of Boethius that was made by King Alfred and he quotes some "Boethian" remarks from Frodo, Treebeard, and Elrond.

Boethius and Consolatio Philosophiae are cited frequently by the main character Ignatius J. Reilly in the Pulitzer Prize-winning A Confederacy of Dunces (1980).

It is a prosimetrical text, meaning that it is written in alternating sections of prose and metered verse. In the course of the text, Boethius displays a virtuosic command of the forms of Latin poetry. It is classified as a Menippean satire, a fusion of allegorical tale, platonic dialogue, and lyrical poetry.

Edward Gibbon described the work as "a golden volume not unworthy of the leisure of Plato or Tully."

In the 20th century, there were close to four hundred manuscripts still surviving, a testament to its popularity.

Of the work, C. S. Lewis wrote: "To acquire a taste for it is almost to become naturalised in the Middle Ages."

Reconstruction of lost songs
Hundreds of Latin songs were recorded in neumes from the ninth century through to the thirteenth century, including settings of the poetic passages from Boethius's The Consolation of Philosophy. The music of this song repertory had long been considered irretrievably lost because the notational signs indicated only melodic outlines, relying on now-lapsed oral traditions to fill in the missing details. However, research conducted by Sam Barrett at the University of Cambridge, extended in collaboration with medieval music ensemble Sequentia, has shown that principles of musical setting for this period can be identified, providing crucial information to enable modern realisations. Sequentia performed the world premiere of the reconstructed songs from Boethius's The Consolation of Philosophy at Pembroke College, Cambridge, in April 2016, bringing to life music not heard in over 1,000 years; a number of the songs were subsequently recorded on the CD ''Boethius: Songs of Consolation. Metra from 11th-Century Canterbury'' (Glossa, 2018). The detective story behind the recovery of these lost songs is told in a documentary film, and a website launched by the University of Cambridge in 2018 provides further details of the reconstruction process, bringing together manuscripts, reconstructions, and video resources.

title: On the Consolation of Philosophy