Boost logo

Boost :

From: Nickolay Mladenov (nikiml_at_[hidden])
Date: 2001-01-12 12:15:48


The += and -= operators will be way more efficient if rewriten as:

template <typename IntType>
rational<IntType>& rational<IntType>::operator+= (const
rational<IntType>& r)
{
    IntType g= gcd(den, r.den)
    den /= g; /one mull removed
    // This calculation avoids overflow
    num = num * (r.den / g) + r.num * (den); //one div removed
    // normalize(); // Example where this is needed: 1/2 + 1/2
    g=gcd(nom,g);
    //this does the normalisation since if h |den,nom => h|g,nom, and it
is better since g is way smaller than den
    nom/=g;
    den *=r.den/g; //reduces the overflow even more
    return *this;
}

template <typename IntType>
rational<IntType>& rational<IntType>::operator-= (const
rational<IntType>& r)
{
    IntType g= gcd(den, r.den)
    den /= g;
    // This calculation avoids overflow
    num = num * (r.den / g) - r.num * (den);
   // normalize(); // Example where this is needed: 1/2 + 1/2
    g=gcd(nom,g);
    nom/=g;
   den *=r.den/g;
   return *this;
}

Nikolay


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