[libcxx-commits] [PATCH] D66836: [libc++] Add `__truncating_cast` for safely casting float types to integers

Zoe Carver via Phabricator via libcxx-commits libcxx-commits at lists.llvm.org
Wed Aug 28 13:46:24 PDT 2019


zoecarver added inline comments.


================
Comment at: include/math.h:1582
+  const _RealT __trunc_r = __builtin_trunc(__r);
+  if (__trunc_r >= ::nextafter(static_cast<_RealT>(_MaxVal), INFINITY)) {
+    return _Lim::max();
----------------
scanon wrote:
> EricWF wrote:
> > scanon wrote:
> > > zoecarver wrote:
> > > > Maybe change `INFINITY` to `std::numeric_limits< _RealT >::infinity()`
> > > Why isn't this just `__trunc_r > _MaxVal`?
> > Consider `long long` and `double`. `MaxVal - numeric_limits<long long>::max() == 1024`, and we want values between `MaxVal` and `::max()` to round down. So instead we essentially check for `__r >= numeric_limits<long long>::max() + 1`. This approach seems more accurate.
> > Consider long long and double. MaxVal - numeric_limits<long long>::max() == 1024, and we want values between MaxVal and ::max() to round down. So instead we essentially check for __r >= numeric_limits<long long>::max() + 1
> 
> Yes, but there are no values between MaxVal and ::max() in the floating-point format; if there were, they would be MaxVal instead. So you can ditch the nextafter and just use `> static_cast<_FloatT>(MaxVal)`.
I thought the same thing, but that isn't necessarily true. Eric showed me this link https://godbolt.org/z/AjBHYqv which does a good job showing what happens when trying to compare an integer value and float value. See the precision loss:
> warning: implicit conversion from 'long long' to 'double' changes value from 9223372036854775807 to 9223372036854775808 


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D66836/new/

https://reviews.llvm.org/D66836





More information about the libcxx-commits mailing list