Math domain error in python when using log

1243
December 15, 2016, at 12:44 PM

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 "<stdin>", line 1, in <module>
ValueError: math domain error

Can someone please explain what I'm doing wrong? Thanks.

Answer 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.
Answer 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.

READ ALSO
Python Scrapy&#39;s ImagesPipeline not working

Python Scrapy's ImagesPipeline not working

I have this in settingspy

401
Preserve DOCTYPE of an lxml.etree parsed xml with namespace

Preserve DOCTYPE of an lxml.etree parsed xml with namespace

This question is almost the same as Preserving original doctype and declaration of an lxmletree parsed xml

486
Cocotb using generics/parameters in gate level simulation

Cocotb using generics/parameters in gate level simulation

I have successfully setup a Cocotb verification environment for my design, and I am happy the way it works for RTL (VHDL in my case)

383