Any way to detect division by zero?

i like this post (click again to cancel)
i dont like this post (click again to cancel)

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

asked Dec 08 '10

Shu gravatar image Shu
153 4 9 19

updated Dec 09 '10

niles gravatar image niles
3725 7 45 104

2 Answers:

i like this answer (click again to cancel)
i dont like this answer (click again to cancel)

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.


posted Dec 08 '10

cswiercz gravatar image cswiercz
839 6 17 33
i like this answer (click again to cancel)
i dont like this answer (click again to cancel)

Something like this:

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


sage: temp(2)
sage: temp(0)

posted Dec 08 '10

John Palmieri gravatar image John Palmieri flag of United States
2970 9 26 67

Your answer

Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!
Login/Signup to Post

Question tools



Asked: Dec 08 '10

Seen: 214 times

Last updated: Dec 09 '10

powered by ASKBOT version 0.7.22
Copyright Sage, 2010. Some rights reserved under creative commons license.