Boolean array indexing and finding multiple zeros of a function at once

The following is a useful coding technique using Boolean array indexing in Python for quickly finding many zeros of a function at once. It avoids having to search for the multiple roots using root-finding functions of various kinds, with inconveniences such as having to identify suitable starting values for the numerical iterations, etc. I will use the complicated function

y = \sin\bigg(\frac{\exp(\sqrt{\pi}\cdot x)}{2\sqrt{2}\cdot x}\bigg)

as an example, which has nine zeros in the interval [0.01, 0.06]. I plotted this in Python as follows:

The nine zeros shown in the plot can be found at once with a single line of code using Boolean indexing:

This single line of code works as follows. We first obtain an array of products of consecutive elements from the y-array using y[1:]*y[:-1]. The array y[1:] starts from the second element of the original y-array and ends at the final element, while the array y[:-1] starts from the first element of the y-array and ends at the penultimate element. The products of consecutive elements from the y-array contained in y[1:]*y[:-1] will all be positive except for products of elements which lie on either side of a zero of the function. Since these elements are of opposite sign, their product will be negative. The only negative values in the array y[1:]*y[:-1] will thus occur at positions corresponding to values of x which are zeros of the function.

Next, we convert the y[1:]*y[:-1] array into a Boolean array by writing y[1:]*y[:-1] < 0. This is now an array of Boolean elements all of whose values are False except those which correspond to the negative values in y[1:]*y[:-1], and these will have the value True. Finally, we use this Boolean array to index the array of x-values, by writing

x[1:][y[1:]*y[:-1]<0]

This picks out only those values of the x-array corresponding to values in the Boolean array which are True, and these are the zeros of the function. (Note that it is necessary to start at the second element of the original x-array to make sure that the dimensions of the arrays x[1:] and y[1:]*y[:-1]<0 are compatible).

Published by Dr Christian P. H. Salas

Mathematics Lecturer

Leave a comment