[Tutor] list comprehension with else

Steven D'Aprano steve at pearwood.info
Mon Jan 19 01:55:53 CET 2015

On Sun, Jan 18, 2015 at 02:20:55PM -0800, Danny Yoo wrote:
> Just to add, log(0) is mathematically undefined.
> https://en.m.wikipedia.org/wiki/Logarithm.

For the record, IEEE-754 specifies that log(0.0) should return -INF. 
That's what Decimal does:

py> from decimal import Decimal
py> Decimal(0).log10()

Alas, Python's math module only has partial support for the IEEE-754 

> So depending on the problem's context, it might be worth asking why log is
> being applied on this input.  Is such input expected?  Make sure the code
> isn't trying to correct for input that shouldn't be there in the first
> place.

Correct. Replacing too small values with 0.0 is the wrong solution. 
Using -INF is better, or a very large negative number. Otherwise, 
sticking 0 in the result is equivalent to replacing the negative values 
with 1.

data = [0.5, 1.0, 0.0]  # Good value, good value, bad value.
# This is the wrong way:
[0.0 if x == 0.0 else math.log(x) for x in data]
=> returns [-0.6931471805599453, 0.0, 0.0]

That is mathematically equivalent to x = 0.0 being replaced with x = 1.0 
before taking the log, and that makes no sense.


More information about the Tutor mailing list