Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make division by zero equal to zero

How can I ignore ZeroDivisionError and make n / 0 == 0?

like image 399
octosquidopus Avatar asked Dec 05 '14 13:12

octosquidopus


People also ask

What is the division of zero by zero?

Because what happens is that if we can say that zero, 5, or basically any number, then that means that that "c" is not unique. So, in this scenario the first part doesn't work. So, that means that this is going to be undefined. So zero divided by zero is undefined.

How do you divide by zero equal to?

A Number Divided by 1 a1=a Just like multiplying by 1, dividing any number by 1 doesn't change the number at all. 0 Divided by a Number 0a=0 Dividing 0 by any number gives us a zero. Zero will never change when multiplying or dividing any number by it.

What happens if you divide 0 by 0 quote?

“What is zero divided by zero?” If you ask Siri this question in the iOS 8 operating system, the iPhone's virtual assistant will cleverly tell you that you're making no sense. “Imagine that you have zero cookies,” Siri's response begins, “and you split them evenly among zero friends.

Who said if you divide 0 by 0?

According to Brahmagupta, A positive or negative number when divided by zero is a fraction with the zero as denominator. Zero divided by a negative or positive number is either zero or is expressed as a fraction with zero as numerator and the finite quantity as denominator. Zero divided by zero is zero.


2 Answers

Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.

def weird_division(n, d):
    return n / d if d else 0
like image 79
davidism Avatar answered Oct 11 '22 11:10

davidism


You can use a try/except block for this.

def foo(x,y):
    try:
        return x/y
    except ZeroDivisionError:
        return 0

>>> foo(5,0)
0

>>> foo(6,2)
3.0
like image 24
Cory Kramer Avatar answered Oct 11 '22 10:10

Cory Kramer