Boost logo

Boost :

From: Jan Langer (jan_at_[hidden])
Date: 2004-01-12 15:40:01

Andy Little wrote:
> I have done a bit of er hacking.
> changed the Add Mult etc to use the MPL versions.
> called it rat for no very good reason:
> using boost::math::rat;
> using boost::mpl::plus;
> typedef plus<rat<2,1>,rat<2,2> >::type Rat;
> Shut your eyes and think of nice things before you take a look
> Header enclosed.

i'd like to suggest the following implementation:

// compile time rational number
template<long N,long D = 1>
struct rat {
     static const long nabs = static_abs<N>::value;
     static const long dabs = static_abs<D>::value;
     // need cast to signed because
     // static_gcd returns unsigned long
     static const long nden_abs = static_cast <long>
     static const long nden = (dabs < 0) ? -nden_abs : nden_abs;

     static const long numerator = N/nden;
     static const long denominator = D/nden;

     typedef rat <numerator, denominator> type;

the double gcd computation can be saved, and the reduce_rat can be
eliminated by using type inside the class.

but the real point i want to make is that reduction does the following:
        rat <1, -2> => rat <-1, 2>,
        rat <-1, -2> => rat <1, 2>
the sign of the denominator is always positive after reduction.

ps: andy, what is the specialization of multiplies and divides good for,
which use the default arg for the second factor's denominator?


jan langer ... jan_at_[hidden]
"pi ist genau drei"

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