# find_root return values This post is a wiki. Anyone with karma >750 is welcome to improve it.

Hi there!

What are return values of find_root in the case when there is no root in the interval?

Thanks!

Archie

edit retag close merge delete

Sort by » oldest newest most voted

When there is no root in the given interval, the function find_root() does not return anything but raises a RuntimeError exception:

sage: f(x) = 2 ; f
x |--> 2
sage: find_root(f,-10,10)
...
RuntimeError: f appears to have no zero on the interval


If you want to deal with that, you have to catch the error (otherwise your program will stop here):

try:
root = find_root(f,-10,10)
root_exist = True
except RuntimeError:
root_exist = False


more

Great answer! Exactly what I wanted, thank you very much! I will post my naive piece of code for finding all roots in given interval. Just in case anyone likes it. Best... This post is a wiki. Anyone with karma >750 is welcome to improve it.

more This post is a wiki. Anyone with karma >750 is welcome to improve it.

def find_all_roots(func,a,b,nsteps):
roots=[]
n=0
x0=a                #initializations
step=(b-a)/(nsteps)     #size of a sub-interval
#the rest is quite self-explanatory
while (n<nsteps):
try:
roots.append(find_root(func,x0,x0+step))
root_exist = True
except RuntimeError:
root_exist = False
x0+=step
n+=1
roots.sort()
return roots

more

Just in case you are interested; there is a root function which does this already with a lot higher precision and more options. def find_all_roots(func,a,b): assume( x>=a , x<=b) try: roots = [cp for cp in (func==0).roots(x, ring=RR, multiplicities=False)] except: roots = [ ] return roots find_all_roots((x+x^2-10), -10,10) returns: [-3.70156211871642, 2.70156211871642] find_all_roots((x^2+1), -10, 10) returns: [ ] (sry about the bad spacing, not sure how to format the text here yet) This post is a wiki. Anyone with karma >750 is welcome to improve it.

I think it raises an error, but surely you can check this very quickly by trying to find a root of x^2 + 1 .

more This post is a wiki. Anyone with karma >750 is welcome to improve it.

## I just wanted to write a piece of code to find ALL roots in given interval by dividing it into small subintervals. I found two difficulties: 1. pay attention if your function makes sense on boarders of the interval you plan to scan (solution -- just pay attention to it); 2. handling the situation when there is no root (solved by the comment of tmonteil, thanks!). The code is primitive and surely not optimal, but it does the job. Find it attached. Good luck! Archie

def find_all_roots(func,a,b,nsteps):
roots=[]
n=0 x0=a #initializations step=(b-a)/(nsteps) #size of a sub-interval #the rest is quite self-explanatory while (n<nsteps): try:="" roots.append(find_root(func,x0,x0+step))="" root_exist="True" except="" runtimeerror:="" <br=""> root_exist = False x0+=step n+=1 roots.sort() return roots

more