5

I am trying to do a logarithm of zero in Python.

from math import log
log(0)

And this raises me an exception.

ValueError: math domain error

I understand that a log of a negative number is mathematically undefined, and that's why Python's log can raise this ValueError exception. But why does it raise also the exception when calling it with a zero value? It should return a -inf value, and I've seen that infinite numbers can be represented in Python (as in here).

Can I deal with this problem without personally treating it? I mean personally when doing something like this.

from math import log, inf
foo = ... # Random value.
if foo != 0: return log(foo)
else: return -inf
Community
  • 1
  • 1
Santiago Gil
  • 1,212
  • 6
  • 18
  • 49

1 Answers1

9

Actually Python is not wrong. The logarithm of zero is also undefined, which is because it's a limit, and it's -inf only from the right, not from the left:

enter image description here

So, no, you have to deal with this yourself. That's wrong, but you can do that. something like this: log(x) if x != 0 else -inf.

The Quantum Physicist
  • 22,970
  • 17
  • 88
  • 165
  • Handle negative numbers, they would return `-inf` too – Adirio Mar 23 '17 at 15:25
  • 1
    `log(x) if x !=0 else -inf`, I think, captures the right idea where a value of `-inf` can be accomodated. It still (correctly) raises an exception for negative `x`. – chepner Mar 23 '17 at 15:32