0

I am trying to calculate the average disorder in ID trees. My code is below:

Republican_yes = yes.count('Republican')
Democrat_yes = yes.count('Democrat')
Republican_no = no.count('Republican')
Democrat_no = no.count('Democrat')
Indep_yes = yes.count('Independent')
Indep_no = no.count('Independent')

disorder_yes= Republican_yes/len(yes)*(math.log(float(Republican_yes)/len(yes),2))+   Democrat_yes/len(yes)*(math.log(float(Democrat_yes)/len(yes),2))+Indep_yes/len(yes)*(math.log(float(Indep_yes)/len(yes),2))

disorder_no= Republican_no/len(no)*(math.log(float(Republican_no)/len(no),2))+Democrat_no/len(no)*(math.log(float(Democrat_no)/len(no),2))+Indep_no/len(no)*(math.log(float(Indep_no)/len(no),2))

avgdisorder = -len(yes)/(len(yes)+len(no))*disorder_yes - len(no)/(len(yes)+len(no))*disorder_no

return avgdisorder

why do I keep getting math domain error?

2
  • Have you tried checking to make sure none of the variable values are zero? That is the most likely problem. Commented Nov 18, 2013 at 4:46
  • Thanks! How do I only choose non-zero values for the formula? Commented Nov 18, 2013 at 5:19

1 Answer 1

1

Check if the lengths are 0 or not, else you will get MathError.

if len(yes):
    disorder_yes= Republican_yes/len(yes)*(math.log(float(Republican_yes)/len(yes),2))+   Democrat_yes/len(yes)*(math.log(float(Democrat_yes)/len(yes),2))+Indep_yes/len(yes)*(math.log(float(Indep_yes)/len(yes),2))

if len(no):
    disorder_no= Republican_no/len(no)*(math.log(float(Republican_no)/len(no),2))+Democrat_no/len(no)*(math.log(float(Democrat_no)/len(no),2))+Indep_no/len(no)*(math.log(float(Indep_no)/len(no),2))

if len(yes) or len(no):
    avgdisorder = -len(yes)/(len(yes)+len(no))*disorder_yes - len(no)/(len(yes)+len(no))*disorder_no

If you want, you can always add the else clause for all 3 if statements as per your requirement.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.