floating point conversion
Famous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 1 09:02:44 PDT 2014
On Sunday, 1 June 2014 at 15:31:53 UTC, Martin Krejcirik wrote:
> On 1.6.2014 16:42, Famous wrote:
>> from string should be the same, exacly, always. Casting a
>> float to
>> double should be deterministic as well.
>
> void main()
> {
> float a = 1.234f;
> double b = 1.234;
> assert (a == cast(float) b); // fails in DMD x86, works in
> GDC, LDC
> }
>
> Maybe enhancement request ?
This is different. The decimal 1.234 cannot be exacly represented
as radix-2 floating-point number. In your example above, a and b
are not equal. They are both approximations to 1.234 but the
value of b is closer. Then casting b to float might or might not
result in the same value as that of a. This is what bearophile
and Qox referred to.
Since every float can be exacly converted to double the following
situation is different:
float a = 1.234f;
double b = a;
assert(a == b); // always succeeds in a sane environment
When taking into account constant folding, well, decide on your
own, whether the following behaviour is sane:
void main()
{
const float a = 1.234f;
float b = 1.234f;
assert(a == 1.234); // ok
assert(b == 1.234); // fails
}
More information about the Digitalmars-d-learn
mailing list