Short-circuit Logic

Chris Angelico rosuav at gmail.com
Tue May 28 10:01:01 EDT 2013


On Tue, May 28, 2013 at 11:48 PM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> py> y = 1e17 + x  # x is not zero, so y should be > 1e17
> py> 1/(1e17 - y)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ZeroDivisionError: float division by zero

You don't even need to go for 1e17. By definition:

>>> sys.float_info.epsilon+1.0==1.0
False
>>> sys.float_info.epsilon+2.0==2.0
True

Therefore the same can be done with 2 as you did with 1e17.

>>> y = 2 + sys.float_info.epsilon
>>> 1/(2-y)
Traceback (most recent call last):
  File "<pyshell#182>", line 1, in <module>
    1/(2-y)
ZeroDivisionError: float division by zero

Of course, since we're working with a number greater than epsilon, we
need to go a little further, but we can still work with small numbers:

>>> x = sys.float_info.epsilon * 2   # Definitely greater than epsilon
>>> y = 4 + x
>>> 1/(4-y)
Traceback (most recent call last):
  File "<pyshell#191>", line 1, in <module>
    1/(4-y)
ZeroDivisionError: float division by zero


ChrisA



More information about the Python-list mailing list