dsign
dsign

Reputation: 12700

Horrible number comes from nowhere

Out of nowhere I get quite a big result for this function... It should be very simple, but I can't see it now.

double prob_calculator_t::pimpl_t::B_full_term() const
{
    double result = 0.0;
    for (uint32_t j=0, j_end=U; j<j_end; j++)
    {
        uint32_t inhabited_columns = doc->row_sums[j];
        // DEBUG
        cout << "inhabited_columns: " << inhabited_columns << endl;
        cout << "log_of_sum[j]: " << log_of_sum[j] << endl;
        cout << "sum_of_log[j]: " << sum_of_log[j] << endl;
        // end DEBUG
        result += ( -inhabited_columns * log( log_of_sum[j] ) + sum_of_log[ j ] );
        cout << "result: " << result << endl;
    }
    return result;
} 

and where is the trace:

inhabited_columns: 1
log_of_sum[j]: 110.56
sum_of_log[j]: -2.81341
result: 2.02102e+10
inhabited_columns: 42
log_of_sum[j]: 110.56
sum_of_log[j]: -143.064
result: 4.04204e+10

Thanks for the help!

Upvotes: 8

Views: 342

Answers (2)

Bathsheba
Bathsheba

Reputation: 234665

inhabited_columns is unsigned and I see a unary - just before it: -inhabited_columns.

(Note that unary - has a really high operator precedence; higher than * etc).

That is where your problem is! To quote Mike Seymour's answer:

When you negate it, the result is still unsigned; the value is reduced modulo 232 to give a large positive value.

One fix would be to write

-(inhabited_columns * log(log_of_sum[j]))

as then the negation will be carried out in floating point

Upvotes: 14

Mike Seymour
Mike Seymour

Reputation: 254431

inhabited_columns is an unsigned type. When you negate it, the result is still unsigned; the value is reduced modulo 232 to give a large positive value.

You should change it to a sufficiently large signed type (maybe int32_t, if you're not going to have more than a couple of billion columns), or perhaps double since you're about to use it in double-precision arithmetic.

Upvotes: 6

Related Questions