First time here? Check out the FAQ!

Ask Your Question
2

Any way to detect division by zero?

asked 14 years ago

Shu gravatar image

updated 14 years ago

niles gravatar image

In Sage, is there any way (function call) to check whether a given expression will produce division by zero error. Is something like the following possible?

if IsDivisionByZero(expr): return False

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
4

answered 14 years ago

You can use Python try...except blocks to catch a ZeroDivisionError. For example, I define the two functions

def foo(x):
    return 1/x

def bar(x):
    try:
        return 1/x
    except ZeroDivisionError:
        # error handling: do whatever you want here
        print "Returning positive infinity..."
        return Infinity

This is what the output looks like when giving various inputs into these two functions.

sage: foo(1)
1
sage: foo(0)
Traceback (click to the left of this block for traceback)
...
ZeroDivisionError: Rational division by zero
sage: bar(1)
1
sage: bar(0)
Returning positive infinity...
+Infinity

You can use try...except blocks outside of function definitions as well.

Preview: (hide)
link
2

answered 14 years ago

Something like this:

def temp(x):
    try:
        return 3/x
    except ZeroDivisionError:
        return False

Then

sage: temp(2)
3/2
sage: temp(0)
False
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: 14 years ago

Seen: 3,147 times

Last updated: Dec 09 '10