Ask Your Question
0

Find out if there is a zero on an interval...and then use that knowledge

asked 2 years ago

Mmmath gravatar image

updated 2 years ago

So, I'm using find_root to figure out if there is a zero on a particular interval for a function. But this is part of a larger program and I want to be able to do something different if there is a root versus if there isn't. The idea is that this has to automate for all manner of functions!

For instance:

f = sin(x)
if find_root(sin(x),1,2) not in RR:
   print(no root)
else:
   print(root)

Now, of course, this doesn't work because find_root just kicks out an error when there isn't a root. Any ideas what I can do instead?

Preview: (hide)

Comments

You may catch this exception and treat it accordingly. see the relevant chapter of the Python tutorial.

But beware : find_root will return one root even if many exist in your interval. Consider :

sage: find_root(sin(t)-1/2, 0, pi)
2.6179938779914944

or, worse :

sage: find_root(sin(1/t)-1/2, 0, 1)
0.3819718634205746

(the point of the latter example being that there is an infinity of solutions in this interval...).

Furthermore, find_root is a numerical solver, whose answers may not learn you puch about the structure of the solution, which is often the point...

HTH,

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2 years ago )

Nice - this is exactly what I need. Fortunately, my whole program is built on approximation by it's very nature, so the rounding is not an issue.

Mmmath gravatar imageMmmath ( 2 years ago )

I'm not so sure : meditate :

sage: find_root(x^2, -1, 1)
-2.7755575615628914e-17
sage: find_root(x^3, -1, 1)
0.0
sage: find_root(x^4-x^2, -1, 1)
-1.0
sage: find_root(x^4, -1, 1)
-1.1102230246251565e-16
sage: find_root(x^3-x, -1, 1)
-1.0
Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2 years ago )

1 Answer

Sort by » oldest newest most voted
2

answered 2 years ago

Mmmath gravatar image

The solution here is to write the following:

try:
    if find_root(sin(x), 1, 2) in RR:
        print("roots")
except RuntimeError:
    print("no roots")

This will figure out IF there are roots in the specified interval, but won't tell you how many there are.

Preview: (hide)
link

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: 2 years ago

Seen: 165 times

Last updated: Jan 10 '23