0

I have tried already available solution but couldn't solve this problem.

original Code:

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

solution: (but I prefer to take common log)

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

As mentioned here: I tried to round the number to 3 decimal places.

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

but I am still getting math domain error.

Edit: I passed the value directly i.e. math.log(0.744) and it works. It also works when I try math.log() function in python console.

Please advise.

Specs:
python 3.6.3
pycharm

omer
  • 522
  • 1
  • 8
  • 26
  • 2
    A math domain error normally occurs when you try to do a mathematically invalid operation, such as log(0) or log(-7). Are you sure that your code never tries to calculate an impossible value? – Atto Allas Nov 30 '17 at 13:33
  • yes I am sure. variable prob is 0.7445791360764896. when I round it to 0.744 it still gives error. then i simply pass `0.744` i.e. math.log(0.744) and it works. It is very strange. – omer Nov 30 '17 at 13:36
  • Are you passing a `Decimal` object to the log function? You may have to convert to `float` first. – pault Nov 30 '17 at 13:44
  • I was not passing a `Decimal` number. Anyway, I have answered the solution. – omer Nov 30 '17 at 14:00

2 Answers2

0

I was getting 0.0.

In my case, Solution is to skip 0.0 value.

if number > 0:
     self.classpriorprob[cls] = math.log(number)
omer
  • 522
  • 1
  • 8
  • 26
  • 1
    It would be better to check `if number > 0` both because the domain of `log` is positive and because checking for exact equality for floating point numbers is not recommended. – pault Nov 30 '17 at 14:00
0

Try using the log sum exp trick:

 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) 
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Madhu
  • 1
  • 2