# Integration over a n-dim. array for each element of a n-dim. result-array

In numerical calculations a well known "problem" can be the integration or summation of an entire array when the result of this summation is required for each field of an equally large array, e.g. in the calculation of the electro static potential of a given charge distribution:

## The Problem

Intuitivaly one would require n nested loops for each dimension of the array representing Φ(x) and another n loops nested within for Q -- thus one would need to write 2*n nested loops in order to get the full sum over Q for each point in Φ.

Especially in Python this approach is rather slow. Even the attempt of writing an appropriate subroutine in C or with Cython will not be the sole measure of writing an efficient code.

## The solution

One can get rid of the n nested loops for Q when exploiting the mathematical properties of NumPy arrays. Instead one can write the term in the divisors of equations (1) and (2) as the simle difference of a scalar represing the current field of Φ and an n-dimensional array specifying all possible x-values for Q. This is quite elegant as one will need this large arrays, too, when the data shall be plotted with correct numbering of the axes.

The above mentioned logic can be found in lines 14 - 22 of the following example. In order to use more CPU cores, if present, for the calculation the nested loops are located within a Python-Thread.

In lines 33 - 47 one can find a charge density distribution describing a rectangle carrying chanrges on its border. The commented lines 68 and 74 would calculate the electric field from the potential and add a quiver plot to the figure, if uncommented

See the source code

Figure 1: Resulting electro static potential for
a ring with positive charges (right bottom) and
a square with negative charge (left top).

## Variation

A little variation of the above problem could contain an a grounded electrode, e.g. at the plane x=0. This problem is treated with image charges behind the grounded plane (see [1]).

See the source code

Figure 2: Electrostatic potential of a charged ring
in front of a grounded plane at x=0

## The elegant solution

There is a variety of problems which require solutions like eq. (1) and (2), but in the case of electrostatics there is a way to regard grounded objects -- or in more general boundary conditions -- in an elegant way: Solving the Lapace- or Poisson equation.

Usage of a PDE (partial differential equation) solver based on e.g. finite elements such as FiPy allows us to define boundary conditions (e.g. grounded plate, electrode on a given potential or charge distribution). Thus one has not to determine the shape of image charges behind a grounded surface.

# References

1. Dall’Agnol, F. F. & Mammana, V. P.
Solution for the electric potential distribution produced by sphere-plane electrodes using the method of images
Revista Brasileira de Ensino de Fisica, 2009, 31, 3503