Ask Your Question

Any way to detect division by zero?

asked 2010-12-08 12:02:45 -0600

Shu gravatar image

updated 2010-12-09 08:04:33 -0600

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

edit retag flag offensive close merge delete

2 answers

Sort by ยป oldest newest most voted

answered 2010-12-08 12:17:53 -0600

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):
        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)
sage: foo(0)
Traceback (click to the left of this block for traceback)
ZeroDivisionError: Rational division by zero
sage: bar(1)
sage: bar(0)
Returning positive infinity...

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

edit flag offensive delete link more

answered 2010-12-08 12:14:32 -0600

Something like this:

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


sage: temp(2)
sage: temp(0)
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


Asked: 2010-12-08 12:02:45 -0600

Seen: 2,092 times

Last updated: Dec 09 '10