Calculating temperature from molecular dynamics simulation My understanding is that temperature is an inherently macroscopic quantity, but I've seen a number of people talk about calculating the temperature of ideal-gas simulations like this one. To take one example, in the final simulation here the author, a physicist, mentions calculating the pressure and temperature of the particles in his simulation.
Is it possible to define temperature for such a system, and to calculate it within a simulation? And how would one go about doing this?
Thanks
 A: The instantaneous temperature of a system of $N$ particles of masses $m_i$ and velocities $v_i$ is
$$ T(t) = \sum_{i=1}^N \frac{m_iv_i^2(t)}{k_BN_f} $$
where $N_f$ equals the number of degrees of freedom, typically $N_f=3N-3$ for fixed total momentum.
Note that the instantaneous temperature will fluctuate 5-10% about the true (thermodynamic) temperature and should therefore be time-averaged.
A: While lemon's answer is of course correct, it is not the only way to calculate the temperature from a molecular dynamics simulation: it can also be obtained from the configurations, that is, the particle coordinates, of the system. This is called "configurational temperature" (see, e.g., this article; pay-walled). The key identity is (for a canonical ensemble)
$$k_\mathrm{B}T = \frac{\langle \mathbf B(\mathbf \Gamma) \cdot \nabla_{\mathbf \Gamma} H(\mathbf \Gamma) \rangle_{\mathbf \Gamma}}{\langle \nabla_{\mathbf \Gamma} \cdot \mathbf B(\mathbf \Gamma) \rangle_{\mathbf \Gamma}}$$
with $B$ an (almost; weak restrictions apply) arbitrary vector field depending on the phase space variables $\Gamma$, $H(\Gamma)$ the Hamiltonian and $\nabla_\Gamma$ the phase space gradient.$\langle \ldots \rangle_\Gamma$ denotes the ensemble average. The fact that $B(\Gamma)$ is basically arbitrary means that you can have $B$ also only depend on the positions and not on the momenta. For example, for $\mathbf B(\mathbf \Gamma) = \nabla E(\mathbf x)$ with $E(\mathbf x)$ being the system's potential energy, the following identity holds:
$$k_\mathrm{B} T = \frac{\langle \nabla E(\mathbf x) \cdot \nabla E(\mathbf x) \rangle}{\langle \nabla \cdot \nabla E(\mathbf x)\rangle}$$
Now $\langle \ldots \rangle$ just denotes the ensemble average with respect to the positions $\mathbf x$.
These and similar, only position-dependent, expressions are especially useful when you do Monte Carlo simulations where you usually don't have access to the kinetic energy of your system (note that this example is especially convenient for MD because you have to calculate $\nabla E(\mathbf x) = -\mathbf F(\mathbf x)$ anyway). The configurational temperature can also be used to estimate interaction potentials, that is, more than one "temperatures", see this article (pay-walled; disclaimer: one of the authors is my PhD supervisor).
