Ask Your Question
2

Numerically find all roots in an interval

asked 2010-12-18 17:42:56 +0100

Just a nobody gravatar image

updated 2010-12-18 17:43:25 +0100

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2010-12-18 20:56:58 +0100

Mike Hansen gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2010-12-18 17:42:56 +0100

Seen: 3,627 times

Last updated: Dec 18 '10