Math domain error in python when using log

回眸只為那壹抹淺笑 提交于 2019-12-31 05:45:31

问题


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.


回答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.



回答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.



来源:https://stackoverflow.com/questions/41015253/math-domain-error-in-python-when-using-log

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!