Boost logo

Boost :

Subject: Re: [boost] [math] potentian bug: iround throws, given double( numeric_limits<int>::min() )
From: Krzysztof Czainski (1czajnik_at_[hidden])
Date: 2011-10-20 10:06:22


2011/10/20 John Maddock <boost.regex_at_[hidden]>

> A thought came to my mind... Theoretically, is it possible for the
>> following
>> conditions to be true?
>> static_cast<float>( std::numeric_limits<int>::min(**) ) <
>> std::numeric_limits<int>::min(**)
>> static_cast<double>( std::numeric_limits<int>::min(**) ) <
>> std::numeric_limits<int>::min(**)
>> static_cast<long double>( std::numeric_limits<int>::min(**) ) <
>> std::numeric_limits<int>::min(**)
>> static_cast<float>( std::numeric_limits<int>::max(**) ) >
>> std::numeric_limits<int>::max(**)
>> static_cast<double>( std::numeric_limits<int>::max(**) ) >
>> std::numeric_limits<int>::max(**)
>> static_cast<long double>( std::numeric_limits<int>::max(**) ) >
>> std::numeric_limits<int>::max(**)
>> After all, casting to floating-point may loose precision... I have no
>> knowledge in this area, so it may be just a silly thought.
>>
>
> Ah, yes: when I fixed this bug I had to disable some of new the tests for
> type float because of that very issue: an integer type converted to type
> float may actually be outside the range of an integer due to rounding during
> the conversion.
>
> John.
>

Ah, thanks for a confirmation...

I am interested in a resolution here, which I would like to implement in a
function I wrote as a more general iround; I call it round_cast():

<code>
template < class R, class T, class Policy >
inline R round_cast( T const& x, Policy const& pol )
{
    BOOST_MATH_STD_USING
    T r = boost::math::round(x,pol);
    if( r > boost::integer_traits<R>::const_max || r <
boost::integer_traits<R>::const_min )
       return static_cast<R>( boost::math::policies::raise_rounding_error(
               "cz::ar::round_cast<target_type,%1%>(%1%)", 0, x, pol ) );
    return static_cast<R>(r);
}

template < class R, class T >
inline R round_cast( T const& x )
{
    return round_cast<R>( x, boost::math::policies::policy<>() );
}
</code>

Regards
Kris


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk