8

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 
3
  • log(foo) if foo > 0 else -inf seems fine Commented Mar 23, 2017 at 15:21
  • 3
    It should return a -inf value No it shouldn't. log(0) is not equal to -inf. It's limit "close to zero" tends to go to -infinity, but value itself is undefined. Commented Mar 23, 2017 at 15:22
  • @not_a_robot that will turn negative values into -inf too and that is not right even with limits Commented Mar 23, 2017 at 15:24

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Handle negative numbers, they would return -inf too
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.
This answer makes no sense, because python has no problem with computing math.log(math.inf). So python is kind of wrong because it treats these two limits differently for apparently no good reason.
@TheQuantumPhysicist I have a master's degree in mathematics, thanks very much for the lecturing. I stand by my claim. One can do one of 3 sensible things. (1) define log on the open interval (0, ∞), (2) define log on the closed interval [0, ∞], making use of the extended real number line or (3) consider an extension to the complex logarithm, in which case the limit of the real part of log(z) as z→0 is always well defined as -∞.
@TheQuantumPhysicist What python does is a weird in-between, implementing the log on (0, ∞] with math.log(math.inf)==math.inf, but math.log(0) raising a ValueError. Other libraries like numpy or scipy give a RunTimeWarning but correctly return -∞. Maybe ask me this next time when you are on maths.stackexchange.com, I have >10k reputation on that platform. The personal attacks are really uncalled for.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.