Re: Reading specific memory address into variable

From: Gianni Mariani (gi2nospam_at_mariani.ws)
Date: 10/20/04


Date: Wed, 20 Oct 2004 07:48:44 -0700

David Casey wrote:

>
> I hadn't thought of using stuff like that, but I have found a way which
> works great and is about as simple as you can get.

great ...

just as well because what I suggested is probably too hard. It can give
you the number of binary significant digits easily but figuring out the
number of decimal significant digits is not that easy.

#include <cmath>

// returns number of the same significant binary digits
int accuracy( double correct, double guess )
{
     if ( correct == guess )
     {
         return -1; // no real answer
     }

     if ( ( correct >= 0 ) != ( guess >= 0 ) )
     {
         return 0;
     }

     int correct_exp;
     double correct_mantissa = std::frexp( correct, &correct_exp );
     int guess_exp;
     double guess_mantissa = std::frexp( guess, &guess_exp );

     if ( correct_exp != guess_exp )
     {
         return 0;
     }

     correct_mantissa = std::frexp( correct_mantissa, &correct_exp );
     guess_mantissa = std::frexp( guess_mantissa, &guess_exp );

     if ( correct_exp != guess_exp )
     {
         return 0;
     }

     int diff_exponent;
     std::frexp( correct_mantissa - guess_mantissa, &diff_exponent );

     return - diff_exponent;
}

#include <iostream>

void testit( double correct, double guess )
{
     static const double log10_2 = log(2.0)/log(10.0);

     int this_accuracy = accuracy( correct, guess );

     std::cout << "accuracy( " << correct << ", " << guess << " ) = " <<
         this_accuracy << "\n";

     // this is funny - a single bit is accurate to 1 decimal digit (i.e
     //1.7 and 1.9
     // hve only 1 bit accuracy but are also accurate to 1 decimal digit

     // this conversion is not good enough
     std::cout << "bogus significant digits = "
          << 1+int(( this_accuracy - 1 ) * log10_2) << "\n";

}

int main()
{

     testit( 0.00011221, 0.0001122 );
     testit( 3.14159, 3.14259 );
     testit( log(3.14159)/log(10.0), log(3.14259)/log(10.0) );
}