Skip to content Skip to sidebar Skip to footer

Math Domain Error In Python When Using Log

Here is what I am writing: >>> import math >>> 2/3*math.log(2/3,2) Here is the error I'm getting: Traceback (most recent call last): File '', line 1

Solution 1:

I'm assuming this is Python 2.7.

In 2.7, 2/3 evaluates to 0 since division floors by default. Therefore you're attempting a log 0, hence the error. Python 3 on the other hand does floating point division by default.

To get the correct behaviour you can either:

  1. from __future__ import division, which gives you Python 3 division behaviour in Python 2.7.
  2. Replace each 2/3 with 2/float(3), or 2/3.0.

Solution 2:

The problem is that you are probably using python 2.7. In this version 2/3 gives as result 0 (zero). And log function is not defined for 0. Try this:

2/3.0*math.log(2/3.0,2)

In Python 3.5 this problem does not happen.

Post a Comment for "Math Domain Error In Python When Using Log"