ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Wed, 08 Dec 2010 19:17:53 +0100Any way to detect division by zero?https://ask.sagemath.org/question/7800/any-way-to-detect-division-by-zero/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
Wed, 08 Dec 2010 19:02:45 +0100https://ask.sagemath.org/question/7800/any-way-to-detect-division-by-zero/Answer by John Palmieri for <p>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? </p>
<p>if IsDivisionByZero(expr):
return False</p>
https://ask.sagemath.org/question/7800/any-way-to-detect-division-by-zero/?answer=11838#post-id-11838Something like this:
def temp(x):
try:
return 3/x
except ZeroDivisionError:
return False
Then
sage: temp(2)
3/2
sage: temp(0)
False
Wed, 08 Dec 2010 19:14:32 +0100https://ask.sagemath.org/question/7800/any-way-to-detect-division-by-zero/?answer=11838#post-id-11838Answer by cswiercz for <p>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? </p>
<p>if IsDivisionByZero(expr):
return False</p>
https://ask.sagemath.org/question/7800/any-way-to-detect-division-by-zero/?answer=11839#post-id-11839You 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.Wed, 08 Dec 2010 19:17:53 +0100https://ask.sagemath.org/question/7800/any-way-to-detect-division-by-zero/?answer=11839#post-id-11839