We describe a method for calculating the exchange and correlation (XC) cont
ributions to the total energy, effective potential, and stress tensor in th
e generalized gradient approximation. We avoid using the analytical express
ions for the functional derivatives of E-xc[rho], which depend on discontin
uous second-order derivatives of the electron density rho. Instead, we firs
t approximate E-xc by its integral in a real space grid, and then we evalua
te its partial derivatives with respect to the density at the grid points.
This ensures the exact consistency between the calculated total energy, pot
ential, and stress, and it avoids the need of second-order derivatives. We
show a few applications of the method, which requires only the value of the
(spin) electron density in a grid (possibly nonuniform) and returns a conv
entional (local) XC potential.