Oplec wrote in news:BBomb.35738$3f.25203

@twister01.bloor.is.net.cable.rogers.com:

Hello,

How can underflow and overflow of the basic arithmetic types be tested

for using standard C++?

For instance, if two long doubles are multiplied together, test whether

or not the result is too large to fit in a long double?

Thank you for your time, Oplec.

For multiplication of ints do:

#include <iostream>

#include <ostream>

#include <iomanip>

#include <limits>

#include <cmath>

bool multiply( int &c, int a, int b)

{

c = a * b;

double d = (

std::log(std::abs(double(a)))

+

std::log(std::abs(double(b)))

)

/

log(2)

;

return d < std::numeric_limits< int >::digits;

}

int main()

{

using namespace std;

int const M = -numeric_limits<int>::max();

int r;

cout << boolalpha << hex;

cout << multiply( r, M / 4, M / 4 ) << ": " << r << endl;

cout << multiply( r, 10, 4 ) << ": " << r << endl;

cout << multiply( r, (M/8) + 1, 2 ) << ": " << r << endl;

cout << multiply( r, (M/2) + 1, 4 ) << ": " << r << endl;

}

You can do that without the double-precision math using bit scaning,

as int( std::log(1 << N)/std::log(2)) == N.

For floating point you may want to take the log's base 10 (std::log10())

and check the results is less than

std::numeric_limits:< FloatType >::max_exponent10 for no-overflow and

greater than std::numeric_limits:< FloatType >::min_exponent10 for

no-underflow.

HTH

Rob.

--

http://www.victim-prime.dsl.pipex.com/