1

In the boost::rational class, if I do

boost::rational<int> r(2,2);
std::cout << r << std::endl;

The result will be 1/1. Is there a way to keep this as 2/2 without having to write a wrapper around the rational class? Ideally, I'd like this to apply to addition as well, so that something like

boost::rational<int> r(2,2);
boost::rational<int> s(2,2);
std::cout << r + s << std::endl;

would yield 4/2 instead of 2/1

Any help would be appreciated!

mikesol
  • 1,177
  • 1
  • 11
  • 20
  • 3
    I doubt that any well-designed rational arithmetic library would allow this. Just keep the desired denominator around in your own code. – Fred Foo May 08 '14 at 09:10
  • 1
    Out of curiosity, could you describe the context where this is necessary? – Marc Glisse May 08 '14 at 09:14
  • 1
    What result would you expect from `1/6 + 1/10`? 4/15 or 16/60? – interjay May 08 '14 at 09:25
  • @interjay `8/30` obviously ;-) – Marc Glisse May 08 '14 at 09:43
  • The context would be representing musical time signatures, which don't reduce. Two measures of 4/4 combined together give one measure of 8/4. I hadn't thought it through, though, and I see that for cases with different denominators there's no clear answer. – mikesol May 09 '14 at 18:54

1 Answers1

1

You can't, by design:

The final fundamental operation is normalizing a rational. This operation is performed whenever a rational is constructed (and assigned in place). All other operations are careful to maintain rationals in a normalized state. Normalization costs the equivalent of one gcd and two divisions.

from http://www.boost.org/doc/libs/1_55_0/libs/rational/rational.html

sehe
  • 374,641
  • 47
  • 450
  • 633