Boost logo

Boost :

From: Andrew D Jewell (ajewell_at_[hidden])
Date: 1999-12-10 11:03:54


Back when I was writing rational number classes (in Ada of all
things) I found that my integers would overflow with only the
slightest provocation. The following changes would make the math less
overflow prone, at the cost of some execution time.

in lcm, change
     return (n * m) / gcd(n, m);
to
     return (n * (m / gcd(n, m));

in += and -= change
         num = num * r.den + den * r.num;
         den *= r.den;
to
        newDen = lcm(den, r.den)
        num = num * (newDen / den) + r.num * (newDen / r.den)
        den = newDen;
        // it might be the case that the result is already normalised
        // in which case there is no extra cost.

I'm sure similar tricks could be used for *= and <, but I'm too lazy
to figure them out again.

adj


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk