half datatype?

Robert Jacques sandford at jhu.edu
Sun Nov 18 15:08:17 PST 2012


On Sun, 18 Nov 2012 05:21:27 -0600, Manu <turkeyman at gmail.com> wrote:

> I've often wondered about having an official 'half' type.
> It's very common in rendering/image processing, supported by most video
> cards (so compression routines interacting with this type are common), and
> it's also supported in hardware by some cpu's.
>
> ARM for instance supports 'half's in hardware, and GCC has an __fp16 type
> which would map nicely if D supported the type in the front end.
>
> The alternative us to use ushort everywhere, which is awkward, because it
> is neither unsigned, nor is it an integer, and it's not typesafe (allows
> direct assignment to ints and stuff)...
> It would be nice if: cast(half)someFloat would yield the proper value, even
> if it is performed in software in most architectures, it could be mapped to
> hardware for those that do it.
>
> It could be done in a library, but then GCC couldn't map it properly to the
> hardware type, and since D has no way to describe implicit casts (that I
> know of?) it becomes awkward to use.
> someFloat = someHalf <- doesn't work, because a cast operator expects an
> explicit cast, even though this is a lossless conversion and should be
> exactly the same as someDouble = someFloat.
>
> Thoughts?
>

Vote--.

The a half data type is already part of std.numeric. From the docs:

// Define a 16-bit floating point values
    CustomFloat!16                                x;     // Using the number of bits
    CustomFloat!(10, 5)                           y;     // Using the precision and exponent width
    CustomFloat!(10, 5,CustomFloatFlags.ieee)     z;     // Using the precision, exponent width and format flags
    CustomFloat!(10, 5,CustomFloatFlags.ieee, 15) w;     // Using the precision, exponent width, format flags and exponent offset bias

    // Use the 16-bit floats mostly like normal numbers
    w = x*y - 1;
    writeln(w);

    // Functions calls require conversion
    z = sin(+x)           + cos(+y);                     // Use uniary plus to concisely convert to a real
    z = sin(x.re)         + cos(y.re);                   // Or use the .re property to convert to a real
    z = sin(x.get!float)  + cos(y.get!float);            // Or use get!T
    z = sin(cast(float)x) + cos(cast(float)y);           // Or use cast(T) to explicitly convert

    // Define a 8-bit custom float for storing probabilities
    alias CustomFloat!(4, 4, CustomFloatFlags.ieee^CustomFloatFlags.probability^CustomFloatFlags.signed ) Probability;
    auto p = Probability(0.5);


More information about the Digitalmars-d mailing list