[Tutor] list comprehension with else
Sydney Shall
s.shall at virginmedia.com
Mon Jan 19 16:33:39 CET 2015
On 19/01/2015 00:55, Steven D'Aprano wrote:
> 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()
> Decimal('-Infinity')
>
>
> Alas, Python's math module only has partial support for the IEEE-754
> standard.
>
>
>> 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.
>
Thanks to both Steven and Danny. I will have to examine my logic again.
Superficially, just setting the very occasional 0.0 value to 0 served,
but it is clearly inappropriate. I will try and find the correct answer
to my problem. I may return for advice, although it is not strictly python.
Many thanks to you both.
--
Sydney
More information about the Tutor
mailing list