# Defining a protected division operator

Is it possible to define a protected division operator in SageMath that turns division by zero into the constant 1? I want to be able to do this when simplifying an expression in Sage. What would be the best approach to it?

edit retag close merge delete

It sounds like you would like to change the behaviour of division in "SymbolicRing" (where simplification is explicitly available). The result would be that you cannot trust the answer at all. Perhaps it is possible to replace the zeros you end up dividing by with a variable, say "zero" and simplify that expression? Then "zero/zero" gets simplified to 1. Then you could substitute "zero=0" afterwards.

Sort by » oldest newest most voted

Well, using Python exceptions, you may define a division function like this:

def div(x, y):
try:
return x/y
except ZeroDivisionError:
return 1


It yields

sage: div(2,3)
2/3
sage: div(2,0)
1
sage: div(x,x-x)
1

more

Thanks for your answer, Eric. Where do I need to define this function so Sage knows about it when evaluating the operation? Also, I'm running a Python script to simplify an equation, so, will it call this function when simplifying it? This is done by the following lines of code:

eq = "div(x0, x1)"
print(sage_eval(eq, locals=local_vars))