Can double's overflow to negative values?

Aly picture Aly · Feb 19, 2013 · Viewed 9k times · Source

Hi I am using the g++ compiler and am experiencing (what I think) is underflow of doubles, is this possible and if so how is the behaviour defined

I have uploaded the csv format of the covariance matrix (51x51) here: http://pastebin.com/r0fx1qsx

This is the code(in c++ requires boost) I am using to calculate the determinant ( I have since switched to long doubles and has not had an effect):

int determinant_sign(const boost::numeric::ublas::permutation_matrix<std ::size_t>& pm)
{
    int pm_sign=1;
    std::size_t size = pm.size();
    for (std::size_t i = 0; i < size; ++i)
        if (i != pm(i))
            pm_sign *= -1.0; // swap_rows would swap a pair of rows here, so we change sign
    return pm_sign;
}

long double determinant( boost::numeric::ublas::matrix<long double>& m ) {
    boost::numeric::ublas::permutation_matrix<std ::size_t> pm(m.size1());
    long double det = 1.0;

    if( boost::numeric::ublas::lu_factorize(m,pm) ) {
        det = 0.0;
    } else {
        for(int i = 0; i < (int)m.size1(); i++)
            det *= m(i,i); // multiply by elements on diagonal
        det = det * determinant_sign( pm );
    }
    return det;
}

The result I am given for the data is -3.59916e-183.

When I run the following matlab code:

M = csvread('path/to/csv');
det(M)
the result I get is:

4.2014e-173

As you can see one is (slightly) positive whereas one is (slightly) negative

Answer

Mats Petersson picture Mats Petersson · Feb 19, 2013

Assuming the floating point unit is operating correctly, it will not overflow to negative values - the result will be "+INF" (positive Infinity) if the value is out of the valid range. This can only happen to signed integers.

It is of course entirely possible to have various errors in a calculation that gives a negative answer when a positive one is expected.