ValueError: math domain error

92 views
Skip to first unread message

fairuz17

unread,
May 22, 2012, 12:13:38 AM5/22/12
to nltk-users
Hi all,
I'm trying to calculate Information Gain of a term/word using this
code:

IG = (-float(N_i)/N_all * math.log(float(N_i)/N_all)) + (float(A)/
N_all * (float(A)/(A+B) * math.log(float(A)/(A+B)))) + (float(C)/N_all
* (float(C)/(C+D) * math.log(float(C)/(C+D))))

with this numbers: A=7, B=23, C=0, D=9, N_i=7, N_all=39

but got this error message:
Traceback (most recent call last):
File "/home/fairosilmi/Documents/IG_selftest1.py", line 50, in
<module>
ig_words[word] = infogain(word)
File "/home/fairosilmi/Documents/IG_selftest1.py", line 38, in
infogain
IG = (-float(N_i)/N_all * math.log(float(N_i)/N_all)) + (float(A)/
N_all * (float(A)/(A+B) * math.log(float(A)/(A+B)))) + (float(C)/N_all
* (float(C)/(C+D) * math.log(float(C)/(C+D))))
ValueError: math domain error

I realize that the problem comes from math.log(C) as C=0. So how can I
avoid this error?

Thanks and best regards.

Matthew Berends

unread,
May 22, 2012, 9:27:49 AM5/22/12
to nltk-...@googlegroups.com, nltk-users
You can either explicitly test for 0, e.g.

result = 0
if x > 0:
result = math.log(x)

Or you can wrap the computation in a try/except:

try:
result = math.log(x)
except ZeroDivisionError as e:
x = 0
# report the error if appropriate
print e

Hope this helps,

Matt
> --
> You received this message because you are subscribed to the Google Groups "nltk-users" group.
> To post to this group, send email to nltk-...@googlegroups.com.
> To unsubscribe from this group, send email to nltk-users+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/nltk-users?hl=en.
>

fairuz17

unread,
May 28, 2012, 3:45:01 AM5/28/12
to nltk-users
ok matt,thanks a lot..

On May 22, 9:27 pm, Matthew Berends <matthewbere...@gmail.com> wrote:
> You can either explicitly test for 0, e.g.
>
> result = 0
> if x > 0:
>     result = math.log(x)
>
> Or you can wrap the computation in a try/except:
>
> try:
>     result = math.log(x)
> except ZeroDivisionError as e:
>     x = 0
>     # report the error if appropriate
>     print e
>
> Hope this helps,
>
> Matt
>
Reply all
Reply to author
Forward
0 new messages