You can write whatever code you want inside the inverse
function, so I would just add an explicit check in there to guard against 0 denominators. Like if q == 0: q_inv = 0
or something like that, however you want to handle that for your application.