2

I seek to convert a uint64_t to double.

The problem is that uint64_t is not neccessarily exactly representable as a double for large uint64_t. So instead I want a range containing lowest and highest doubles surrounding the uint64_t.

So if a cast always rounds down.

#include <cmath>
#include <cstdint>
#include <limits>
#include <tuple>

std::tuple<double, double> Intervall(uint64_t n) {
  auto lower = static_cast<double>(n);
  auto upper =
      RoundUpToDouble(n) == lower
          ? lower
          : std::nextafter(lower, std::numeric_limits<double>::infinity());
  return std::make_tuple(lower, upper);
}

So the supplied code is wrong if

  1. static_cast doesn't round downwards

  2. Needs RoundUpToDouble which I don't know how to implement

What method can I use to get the lower and upper bound?

Bomaz
  • 1,871
  • 1
  • 17
  • 22
  • Do you just want to set the rounding mode, or do you want an algorithm that works with the default? – Davis Herring Dec 07 '19 at 02:55
  • a nothrow algorithm modified by no global state is preferable but setting rounding mode is acceptable as long as it works with multithreading – Bomaz Dec 07 '19 at 10:52
  • The rounding mode is thread-specific, so that answer is trivial. – Davis Herring Dec 07 '19 at 16:36
  • I tried setting the rounding. Unfortunately it seems to be implementation dependent which makes it useless. Or am I doing it wrong? https://godbolt.org/z/qxxk2c – Bomaz Dec 07 '19 at 23:50

0 Answers0