Search code examples
cmathlogarithm

Log calls return NaN in C


I have an array of double:

double theoretical_distribution[] = {1/21, 2/21, 3/21, 4/21, 5/21, 6/21};

And I am trying to computer it's entropy as:

double entropy = 0;

for (int i = 0; i < sizeof(theoretical_distribution)/sizeof(*theoretical_distribution); i++) {
    entropy -= (theoretical_distribution[i] * (log10(theoretical_distribution[i])/log10(arity))); 
}    

However I am getting NaN, I have checked the part

(theoretical_distribution[i] * (log10(theoretical_distribution[i])/log10(arity)))  

And found it to return NaN itself, so I assume it's the culprit, however all it's supposed to be is a simple base conversion of the log? Am I missing some detail about the maths of it?
Why is it evaluating to NaN.


Solution

  • You are passing 0 to the log10 function.

    This is because your array theoretical_distribution is being populated with constant values that result from integer computations, all of which have a denominator larger than the numerator.

    You probably intended floating computations, so make at least one of the numerator or denominator a floating constant.