Python math.log函数数学域错误
使用以下代码:Python math.log函数数学域错误,python,math,division,Python,Math,Division,使用以下代码: import math -2/3*math.log(2/3,2)-1/3*math.log(1/3,2) 给出: ValueErrorTraceback(最近一次呼叫上次) 在() 1导入数学 ---->2-2/3*数学日志(2/3,2)-1/3*数学日志(1/3,2) ValueError:数学域错误 其中: import math -.66*math.log(.66,2)-1/3*math.log(.33,2) 工作 第一个代码有什么问题?只有在Python2中才会出现,
import math
-2/3*math.log(2/3,2)-1/3*math.log(1/3,2)
给出:
ValueErrorTraceback(最近一次呼叫上次)
在()
1导入数学
---->2-2/3*数学日志(2/3,2)-1/3*数学日志(1/3,2)
ValueError:数学域错误
其中:
import math
-.66*math.log(.66,2)-1/3*math.log(.33,2)
工作
第一个代码有什么问题?只有在Python2中才会出现,在Python2中,
/
是整数之间的整数除法运算符:1/3
导致0
-并且不可能在零上使用math.log
在Python3中,
/
始终是浮点除法运算符:1/3
是0.3333
。(整数除法被移动到/
)因此,发布的代码不会在Python 3中导致错误。我猜这是Python 2,对吗
在Python 2中,两个整数之间的/
运算符执行,只保留小数点左侧的部分。因此,在Python 2中,表达式的计算结果如下:
-1*math.log(1,2)-1/3*math.log(02)
从这里,很容易看出为什么会出现错误
另一种方法是导入\uuuuu future\uuuu
除法运算符,其行为与您期望的一样:
from __future__ import division
如果您使用的是Python 2,那么就使用Python 3。这似乎与您使用的Python版本有关,出于好奇,您使用的是哪个版本?