handling T.min the right way

Daniel Keep daniel.keep.lists at gmail.com
Tue Mar 20 17:30:38 PDT 2007



Bill Baxter wrote:
> Andrei Alexandrescu (See Website For Email) wrote:
>> Don Clugston wrote:
>>> Andrei Alexandrescu (See Website For Email) wrote:
>>>> A while ago, C++ did the mistake of defining
>>>> std::numeric_limits<T>::min() with a different semantics for
>>>> floating-point types than for integral types. That hurt generic
>>>> numeric code a lot.
>>>>
>>>> D has taken over the same mistake: T.min means the smallest value of
>>>> the type, except for floating-point types, where it means the
>>>> smallest positive value.
>>>>
>>>> The right way is to have T.min always return the minimum value (duh)
>>>> and define a separate property T.min_positive.
>>>>
>>>> The question is, would a lot of code be hurt by such a change?
>>>>
>>>>
>>>> Andrei
>>>
>>> It probably wouldn't break a huge amount of D code, but I don't think
>>> there would be many cases where T.min for a floating point type would
>>> be useful. More significant is the problems involved in converting
>>> from C or Fortran code to D.
>>
>> I'm not even discussing the utility of min_positive. All I'm saying is
>> that if you say "min", you should return "min", particularly when
>> others do exactly that.
>>
>>> On a more profound level...
>>> I'm not aware of many cases where it's possible to treat integer and
>>> floating-points generically. People often try, but usually the code
>>> is incorrect for the floating point types, since the semantics are
>>> completely different. (For example, I don't know why x++ is legal for
>>> floating point types; I think it's just a newbie trap; you have no
>>> guarantee that x++ is different to x).
>>>
>>> What type of generic numeric code did you have in mind? What are the
>>> benefits which would come by such a change?
>>
>> Trivially simple: the min and max functions. For min, the code picks
>> the type with the smallest .min. For max, the code picks the type with
>> the largest .max.
>>
>>
>> Andrei
> 
> 
> Also when you're say trying to find the maximum of a set of numbers it
> can be handy to initialize the 'current_max' to the smallest number
> possible.
> 
> float max_val = float.min; // want the new meaning here
> int max_idx = -1;
> foreach(i,x; bunch_o_floats) {
>    if (x<max_val) {
>        max_val=x;
>        max_idx=i;
>    }
> }
> 
> --bb

I usually cheat and use nan, then change the comparison so that it will
succeed if 'x' is any real number :P

That way, if I give it an empty list, I get nan back instead of
float.min, which could be misleading.

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list