varantir
varantir

Reputation: 6854

Finding all roots in a given interval in 1d

In order to complement the question raised here, I would like to ask how I can find all roots in a certain interval, up to some granularity. Right now I use the poor man's approach and find roots by

import numpy as np
x = np.linspace(0,10,1000)
data = np.sin(x)
roots = (np.abs(data) < 0.1)
# Cluster the data using some other poor man's approach

Upvotes: 1

Views: 1289

Answers (2)

user1196549
user1196549

Reputation:

It should be obvious that without any information on the function at hand, the poor man's approach is optimal (in some probabilistic sense).

Because the roots of general functions a spread uniformly and independently of each other, so that unequal steps, possibly based on the function values, would be a waste of time.

You are in a better position when you can exploit some property of the function. For instance, if you have a bound on the derivative in an interval, for suitable values of the function at the endpoints you can show that no root can be present.

Upvotes: 1

AGN Gazer
AGN Gazer

Reputation: 8378

I do not think there is a magical method that would find all roots of a general equation. Your "poor man's approach" is not too bad to start with. I would use product instead of |data|<eps. For example,

dp = data[1:] * data[:-1]
indices = np.where(dp <= 0)

would provide the location of the "suspicious" intervals. Then you can run a better method providing as initial guess every such suspicious interval's center coordinate. A more sophisticated method maybe could adapt to the slope and adjust function sampling instead of having a constant one like you get with linspace().

Upvotes: 0

Related Questions