What is a concise way to test if floating point value is integral?

Simen Kjaeraas simen.kjaras at gmail.com
Thu Aug 29 06:51:59 PDT 2013


On 2013-08-29, 10:25, Jonathan M Davis wrote:

> On Thursday, August 29, 2013 10:07:31 Paul Jurczak wrote:
>> On Thursday, 29 August 2013 at 07:51:40 UTC, Jonathan M Davis
>> wrote:
>> [..]
>>
>> > as any integral value in a float will fit in an
>> > int.
>>
>> [..]
>>
>> Will it? Most of them will not fit
>
> Sure, they will. float has 32 bits, just like int, so it can't possibly  
> hold a
> value larger than an int can hold. This code passes with flying colors
>
>     foreach(i; int.min .. int.max)
>         assert(cast(float)i == i);

First, that's showing the exact opposite of what you're saying it does.
Second, it doesn't even show that.

Your code is equivalent to:

     foreach(i; int.min .. int.max)
         assert(cast(float)i == cast(float)i);

If that does not pass with flying colors, I'd be surprised. Now try this:

     foreach(i; int.min .. int.max) {
         float f = i; // DMD optimizes out cast(int)cast(float)int
         assert(cast(int)f == i);
     }

It will fail for odd numbers in the range 16,777,216-33,554,432, and for
numbers not divisible by 4 in the range to the next power of two, then 8,
and so on. These numbers are simply not representable by a float.

For more information:
http://floating-point-gui.de/formats/fp/

-- 
   Simen


More information about the Digitalmars-d-learn mailing list