In micromagnetic simulations, the magnetization in one simulation cell is acted upon by the demagnetization field that is generated by all simulation cells. In simulations with periodic boundary conditions, this leads to an infinite number of interactions that have to be taken into account. A method is presented that allows for an accurate calculation of the demagnetization tensor with one and two-dimensional periodic boundary conditions using a small amount of computation time. The method has been implemented in a micromagnetic simulation tool. For a reasonable accuracy and two-dimensional periodic boundary conditions the presented method is about six orders of magnitude faster than the straightforward method in which all cells beyond a certain distance are neglected.