Differences in results when using the same function in CTFE and Runtime

Carsten Schlote carsten.schlote at gmx.net
Thu Aug 8 10:31:32 UTC 2024


Hi

I'm playing with CTFE in D. This feature allows for a lot of 
funny things, e.g. initialisation of immutable data at compile 
time with the result of some other function (template).

As a result I get immutable result blobs compiled into the 
binary. But none of the generating code, because it was already 
executed by CTFE.

This worked nicly for several other usecases as well.For now the 
results of CTFE and RT were always the same. As expected.

However, yesterday a unit-test started to report, that the 
results created by the same code with same parameters differ when 
run in CTFE mode or at runtime.

```D
     static immutable ubyte[] burningShipImageCTFE = 
generateBurningShipImage(twidth, theight, maxIter);
     immutable ubyte[] burningShipImageRT = 
generateBurningShipImage(twidth, theight, maxIter);
     assert(burningShipImageCTFE == burningShipImageRT, "Same 
results expected.");

```
I diffed the pictures and indeed some of the pixels in the more 
complex areas of the BurningShip fractal were clearly and 
noteably different.

Ok, the fractal code uses 'double' floats, which are by their 
very nature limited in precision. But assuming that the math 
emulation of CTFE works identical as the CPU does at runtime, the 
outcome should be identical.

Or not, in some cases ;-) E.g. with a fractal equation where 
smallest changes can result into big differences.

And it opens up some questions:

- Can CTFE be used under all circumstances when float numbers of 
any precision are involved?
- Or is this some kind of expected behaviour whenever floats are 
involved?
- Is the D CTFE documentation completely covering such possible 
issues?

I can imagine that bugs causes by such subtil differences might 
be very difficult to fix.


Any experiences or thought on this?

Greetz
Carsten







More information about the Digitalmars-d mailing list