Any way to detect division by zero?

i like this post (click again to cancel)
2
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
http://nilesjohnson.net/

2 Answers:

i like this answer (click again to cancel)
4
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):
    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.

link

posted Dec 08 '10

cswiercz gravatar image cswiercz
839 6 17 33
http://www.cswiercz.info/
i like this answer (click again to cancel)
2
i dont like this answer (click again to cancel)

Something like this:

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

Then

sage: temp(2)
3/2
sage: temp(0)
False
link

posted Dec 08 '10

John Palmieri gravatar image John Palmieri flag of United States
2970 9 26 67
http://www.math.washingto...

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

Tags:

Stats:

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.