# obtaining all numerical roots of a function in an interval

I'm working on single variable calculus here: Basically what I need is what "find_root" does, but I need a list of ALL roots in a given interval, not just one.

So I've been playing with "solve". I found this piece of code which works in most cases:

sage: roots = solve(f(x),x,solution_dict=True)

sage: roots = [s[x] for s in roots]

sage: num_roots = map(n, roots)

but it gives an error if the function is periodic and has inifinite roots, becuase the symbolic expression that "solve" gets has infinite solutions too.

Defining a desired interval should solve this issue, but I have no idea how to implement such thing!

Thanks you and have a good day.

edit retag close merge delete

Sort by » oldest newest most voted def find_root_recursive(func,a,b,tol=0.000000000001):
L = []
try:
x0 = find_root(func,a,b)
L.append(x0)
L += find_root_recursive(func,a,x0-tol,tol)
L += find_root_recursive(func,x0+tol,b,tol)
except:
pass
return L

L = find_root_recursive(sin,-50,50)
L.sort()
L

more

Formally, it can't be done. For example, $\sin\displaystyle\frac{1}{x}$ has an infinity of roots between -1 and 1...

more If you run the following code you get [-0.973248989467730, 0.973248989467730, -0.229752920547361, 0.229752920547361], but if you uncomment assume(x>0) you get [0.973248989467730, 0.229752920547361].

x=var('x')
#assume(x>0)
f(x) = -x*x+x**4+0.05
roots = solve(f(x),x,solution_dict=True)
roots = [s[x] for s in roots]
num_roots = map(n, roots)
print num_roots

more

Thanks for the reply, but this does not fix the problem with periodic infinte roots. I run into the same error: Traceback (most recent call last): MT = maxim(f, a, b) File "", line 1, in <module> File "/tmp/tmpGBdQkB/___code___.py", line 8, in <module> MT = maxim(f, a, b) File "/tmp/tmpbtKw0f/___code___.py", line 20, in maxim roots = [s[x] for s in roots]; KeyError: x

yes. it is: f(x) = 8 x^3 sin(x^2)-12 x cos(x^2) , or simply (cos(x^2))'''. But I believe the problem happens with any function with inifinite roots.

For cos(x*x) I get two roots [-1/2*sqrt(pi)*sqrt(2), 1/2*sqrt(pi)*sqrt(2)], but I don't get any error.