www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Floating point constant folding

reply Guillaume Chatelet <chatelet.guillaume gmail.com> writes:
Context: 
http://forum.dlang.org/post/qybweycrifqgtcssepgx forum.dlang.org

---  prints 1 ---
void main(string[] args)
{
     import std.stdio;
     import core.stdc.fenv;
     fesetround(FE_UPWARD);
     writefln("%.32g", 1.0f + float.min_normal);
}
---

--- prints 1.00000011920928955078125 ---
void main(string[] args)
{
     import std.stdio;
     import core.stdc.fenv;
     fesetround(FE_UPWARD);
     float x = 1.0f;
     x += float.min_normal;
     writefln("%.32g", x);
}
---

Considering the floating point operations have a runtime 
component, it seems to me that constant folding is not allowed to 
occur in the first example. For example, it does not occur in the 
following C++ snippet:
---
#include <limits>
#include <cstdio>
#include <cfenv>

int main(int, char**) {
     std::fesetround(FE_UPWARD);
     printf("%.32g\n", std::numeric_limits<float>::denorm_min() + 
1.0f);
     return 0;
}
---

Thoughts?
Mar 03
parent reply Johan Engelen <j j.nl> writes:
On Friday, 3 March 2017 at 09:31:19 UTC, Guillaume Chatelet wrote:
 
 Considering the floating point operations have a runtime 
 component, it seems to me that constant folding is not allowed 
 to occur in the first example. For example, it does not occur 
 in the following C++ snippet:
 ---
 #include <limits>
 #include <cstdio>
 #include <cfenv>

 int main(int, char**) {
     std::fesetround(FE_UPWARD);
     printf("%.32g\n", std::numeric_limits<float>::denorm_min() 
 + 1.0f);
     return 0;
 }
Clang without/with optimizations turned on: ❯ clang++ float.cpp && ./a.out 1.00000011920928955078125 ❯ clang++ float.cpp -O3 && ./a.out 1 -Johan
Mar 03
next sibling parent Guillaume Chatelet <chatelet.guillaume gmail.com> writes:
On Friday, 3 March 2017 at 22:35:15 UTC, Johan Engelen wrote:
 Clang without/with optimizations turned on:
 ❯ clang++ float.cpp && ./a.out
 1.00000011920928955078125

 ❯ clang++ float.cpp -O3 && ./a.out
 1

 -Johan
Thx Johan I should have checked... My point is moot then. -- "welcome to the magician world" - Don Clugston | DConf2016
Mar 03
prev sibling parent Fool <fool dlang.org> writes:
On Friday, 3 March 2017 at 22:35:15 UTC, Johan Engelen wrote:
 Clang without/with optimizations turned on:
 ❯ clang++ float.cpp && ./a.out
 1.00000011920928955078125

 ❯ clang++ float.cpp -O3 && ./a.out
 1

 -Johan
GCC with optimizations turned on: $ g++ float.cpp -O3 -frounding-math && ./a.out 1.00000011920928955078125
Mar 03