Casting double to ulong weirdness

bachmeier via Digitalmars-d digitalmars-d at puremagic.com
Mon Aug 24 18:27:16 PDT 2015


On Monday, 24 August 2015 at 21:34:23 UTC, Márcio Martins wrote:
>>> Whatever the issue is, it is not unavoidable, because as has 
>>> been shown,
>>> other languages do it correctly.

There's no guarantee that it will be done consistently or 
correctly in C or C++ to my knowledge. Some compilers will do it 
consistently, but it's absolutely not portable.

>> It is an issue of precision. In order to change from real to 
>> double, some bits must be lost. Since certain numbers cannot 
>> be represented, the CPU must round or truncate.
> There is no mention of real anywhere in any code. The intent is 
> clearly stated in the code and while I accept precision and 
> rounding errors, especially because DMD has no way to select a 
> floating point model, that I am aware of, at least, it's very 
> hard for me to accept the inconsistency.

It's fully consistent with what DMD claims to do:

http://dlang.org/portability.html

While a compiler can guarantee consistency, I don't know of any 
way to guarantee correctness, which makes the question of 
consistency irrelevant. There's no way to know what will happen 
when you run the program.

> What is the correct way to truncate, not round, a 
> floating-point value to an integer?

If you can be an epsilon above or below the exact answer, there's 
no way to guarantee correctness unless you know you're not doing 
something that resembles integer operations. If the exact answer 
is 12.2 or 12.6, you can do it correctly. If it is 12.0 or 23.0, 
you can get the wrong answer.


More information about the Digitalmars-d mailing list