【问题标题】:Math Domain error on math.logmath.log 上的数学域错误
【发布时间】:2017-11-30 13:28:01
【问题描述】:

我尝试了现有的解决方案,但无法解决这个问题。

原代码:

 prob = n / self.totaldocs # 0.7445791360764896
 self.classpriorprob[cls] = math.log(prob) 

解决方案:(但我更喜欢取普通日志)

prob = n / self.totaldocs
d = Decimal(prob) 
self.classpriorprob[cls] = d.ln()

here 所述:我尝试将数字四舍五入到小数点后三位。

prob = n / self.totaldocs
number = round(prob, 3) # 0.744
self.classpriorprob[cls] = math.log(number)

但我仍然遇到数学域错误。

编辑:我直接传递了值,即 math.log(0.744) 并且它有效。 当我在 python 控制台中尝试 math.log() 函数时,它也可以工作。

请指教。

规格
蟒蛇 3.6.3
pycharm

【问题讨论】:

  • 当您尝试执行数学上无效的操作(例如 log(0) 或 log(-7))时,通常会发生数学域错误。您确定您的代码从不尝试计算不可能的值吗?
  • 是的,我确定。变量概率为 0.7445791360764896。当我将它四舍五入到 0.744 时,它仍然给出错误。然后我只需通过 0.744 即 math.log(0.744) 就可以了。很奇怪。
  • 您是否将Decimal 对象传递给日志函数?您可能需要先转换为float
  • 我没有传递Decimal 号码。无论如何,我已经回答了解决方案。

标签: python math logarithm


【解决方案1】:

我得到了 0.0。

就我而言,解决方案是跳过 0.0 值。

if number > 0:
     self.classpriorprob[cls] = math.log(number)

【讨论】:

  • 最好同时检查if number > 0,因为log 的域是正数,并且不建议检查浮点数是否完全相等。
【解决方案2】:

尝试使用 log sum exp 技巧:

 def findMaxArray(self,arr):
        maxValue = arr[0]
        for i in range(0, len(arr)):
            if(maxValue <arr[i]):
                maxValue = arr[i]
        return maxValue


    def logExpSum(self, arr ):
        #find maximum of array assuming the array passed is already containg log values
        maxVal =0
        maxVal= self.findMaxArray(arr)
        res = 0
        for i in range(0, len(arr)):
            res += math.exp (arr[i] - maxVal) 
        return (math.log(res)+ maxVal) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多