3

Using the following bit of code compiled against boost 1.62:

#include <boost/rational.hpp>
#include <iostream>

int main() {
    auto val = boost::rational<int64_t>(499999, 2);
    std::cout << val << std::endl;
    std::cout << boost::rational_cast<double>(val) << std::endl;
}

I get the following output:

499999/2
250000

I would expect rational_cast to output 249999.5 Can anyone explain what I am doing wrong?

user4436000
  • 413
  • 4
  • 7
  • It seems that even the literal `249999.5` is getting rounded off to `250000`, which makes no sense to me. This isn't a Boost thing but I can't explain why numbers so small are being represented inexactly. – Silvio Mayolo Feb 01 '18 at 23:24
  • 1
    Does this assert(val < 250000) works? I'm saying this because possibly your `std::setprecision()` is not good enough for `std::cout`. – AdvSphere Feb 01 '18 at 23:31
  • assert(val < 250000) passes. Playing around with setprecision does not seem to have an effect. – user4436000 Feb 01 '18 at 23:36
  • I have to disagree with the dup. The dup is asking how to do rounding without involving floating points. This is asking why there is imprecision occurring at all and, as my earlier comment indicated, this is not actually dependent on Boost at all. – Silvio Mayolo Feb 02 '18 at 00:18
  • 1
    This works: `std::cout << std::fixed << boost::rational_cast(v) << std::endl;` – AdvSphere Feb 02 '18 at 00:20
  • 1
    @sehe The "duplicate" you are forwarding to is a different situation than this one. assert(v < 25000) works, meaning is not a rounding problem on the rational number, but instead on the output cast. It was a matter of adding `std::fixed` to `std::cout`. – AdvSphere Feb 02 '18 at 00:22
  • 1
    @AdvSphere :raises-brow: I've reopened it for you, now, I will re-read later – sehe Feb 02 '18 at 00:34

1 Answers1

5

Modify the default formatting for floating-point input/output: std::cout << std::fixed << boost::rational_cast<double>(v) << std::endl; add std::fixed to it.

AdvSphere
  • 986
  • 7
  • 15