Thread overview | |||||
---|---|---|---|---|---|
|
April 21, 2020 float has too much precision | ||||
---|---|---|---|---|
| ||||
I'm dumbfounded, why does the following code write '35' on DMD32 D Compiler v2.091.0-dirty? module magic; float magic( float f ) { return f + 35f - f; } void main() { import std.stdio; writeln( magic(1_000_000_000f) ); } |
April 21, 2020 Re: float has too much precision | ||||
---|---|---|---|---|
| ||||
Posted in reply to Faux Amis | On 4/21/20 3:47 PM, Faux Amis wrote:
> I'm dumbfounded, why does the following code write '35' on DMD32 D Compiler v2.091.0-dirty?
>
> module magic;
>
> float magic( float f )
> {
> return f + 35f - f;
> }
>
> void main()
> {
> import std.stdio;
> writeln( magic(1_000_000_000f) );
> }
On run.dlang.io, it prints 64. Also on my mac.
Possibly it's working because intermediate floating point calculations are generally done at max precision. On your system, that might be 80-bit reals.
Also possible that some optimization is figuring out that it can just return 35f?
Try instead:
float magic( float f)
{
float result = f + 35f;
return result - f;
}
Is it worth worrying about? floating point is supposed to be inexact and subject to variance on different machines.
-Steve
|
April 21, 2020 Re: float has too much precision | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | On 2020-04-21 22:10, Steven Schveighoffer wrote:
> On 4/21/20 3:47 PM, Faux Amis wrote:
>> I'm dumbfounded, why does the following code write '35' on DMD32 D Compiler v2.091.0-dirty?
>>
>> module magic;
>>
>> float magic( float f )
>> {
>> return f + 35f - f;
>> }
>>
>> void main()
>> {
>> import std.stdio;
>> writeln( magic(1_000_000_000f) );
>> }
>
> On run.dlang.io, it prints 64. Also on my mac.
>
> Possibly it's working because intermediate floating point calculations are generally done at max precision. On your system, that might be 80-bit reals.
>
> Also possible that some optimization is figuring out that it can just return 35f?
>
> Try instead:
>
> float magic( float f)
> {
> float result = f + 35f;
> return result - f;
> }
>
> Is it worth worrying about? floating point is supposed to be inexact and subject to variance on different machines.
>
> -Steve
No, it doesn't matter. I just wanted to understand why it happened.
It seems splitting it up did the trick. So intermediate it is.
Thanks!
|
Copyright © 1999-2021 by the D Language Foundation