Boost logo

Boost :

From: Andras Erdei (aerdei_at_[hidden])
Date: 2004-12-11 05:03:24

i think the documentation on boost::rational is
misleading, and it cannot be used with finite
precision (e.g. the built-in) types at all:
whenever the result of an operation cannot be
represented exactly, it returns something totally

for example with rational<short> let's try to
add 191/181 (=1.055...) and 197/193 (=1.021...)
the exact result is 72520/34933 (=2.076...),
and we get 6984/-30603 (=-0.229...)!

i don't think the intended audience can "code in
anticipation of such issues" (the task of determining
when these issues come up has the same complexity as
doing the actual arithmetic)

imho this also means that the pre-calculated gcd() trick
in op+= doesn't buy much: finite precision calculations
will still fail randomly and my guess would be that
it only makes unlimited precision calculations slower
(2 gcd() calls + 4 op/()s instead of 1 gcd() call)

fixing rational<> to work with finite precision integers
so that for calculations like the above we get the best
representable approximation (in this case 3197/1540 =
2.076, precise to 7 digits) is pretty straightforward
-- the gcd() function implicitly calculates all
representable approximations -- but would require
rewriting the whole class


Boost list run by bdawes at, gregod at, cpdaniel at, john at