[Issue 360] Compile-time floating-point calculations are sometimes inconsistent

Walter Bright newshound at digitalmars.com
Fri Sep 22 01:27:33 PDT 2006


d-bugmail at puremagic.com wrote:
> ------- Comment #5 from clugdbug at yahoo.com.au  2006-09-22 02:25 -------
> (In reply to comment #4)
>> while (j <= (1.0f/STEP_SIZE)) is at double precision,
>> writefln((j += 1.0f) <= (1.0f/STEP_SIZE)) is at real precision.
> I don't understand where the double precision comes from. Since all the values
> are floats, the only precisions that make sense are float and reals.

The compiler is allowed to evaluate intermediate results at a greater 
precision than that of the operands.

> Really, 0.2f should not be the same number as 0.2.

0.2 is not representable exactly, the only question is how much 
precision is there in the representation.

> When you put the 'f' suffix
> on, surely you're asking the compiler to truncate the precision.

Not in D. The 'f' suffix only indicates the type. The compiler may 
maintain internally as much precision as possible, for purposes of 
constant folding. Committing the actual precision of the result is done 
as late as possible.

> It can be
> expanded to real precision later without problems. Currently, there's no way to
> get a low-precision constant at compile time.

You can by putting the constant into a static, non-const variable. Then 
it cannot be constant folded.

> (In fact, you should be able to write real a = 0.2 - 0.2f; to get the
> truncation error).

Not in D, where the compiler is allowed to evaluate using as much 
precision as possible for purposes of constant folding. The vast 
majority of calculations benefit from delaying rounding as long as 
possible, hence D's bias towards using as much precision as possible.

The way to write robust floating point calculations in D is to ensure 
that increasing the precision of the calculations will not break the result.

Early versions of Java insisted that rounding to precision of floating 
point intermediate results always happened. While this ensured 
consistency of results, it mostly resulted in consistently getting 
inferior and wrong answers.



More information about the Digitalmars-d-bugs mailing list