# Numerically find all roots in an interval

Is there a function to find all the roots of a function on a given interval? I'm thinking of something like this:

sage: find_all_roots(lambda z: tan(z)+z/sqrt(9*pi^2-z^2), 0, 10)
[0, 2.835952326711582867481259929, 5.64146101037285257526886564, 8.338774576412169721334841011]


Thanks!

edit retag close merge delete

Sort by » oldest newest most voted I don't think that there's anything in Sage, but you can use something like the following function:

def find_all_roots(f, a, b, eps=0.0000000001):
roots = []
intervals_to_check = [(a,b)]
while intervals_to_check:
start, end = intervals_to_check.pop()
try:
root = find_root(f, start, end)
except RuntimeError:
continue
if root in roots:
continue
if abs(f(root)) < 1:
roots.append(root)
intervals_to_check.extend([(start, root-eps), (root+eps, end)])
roots.sort()
return roots


It then behaves like the following:

sage: f =  tan(z)+z/sqrt(9*pi^2-z^2)
sage: find_all_roots(f, 0, 9.4)
[0.0, 2.8359523267114892, 5.6414610103726988, 8.3387745764121703]


Note that I had to change the endpoint since find_root does not like it when the function is not defined.

more