Boost logo

Boost Users :

Subject: Re: [Boost-users] [math] round to fraction
From: John Maddock (boost.regex_at_[hidden])
Date: 2010-10-26 13:01:43


> I couldn't find a functionality like 'round to fraction', which would try
> round a floating point value to its nearby fraction portion:
>
> round2fraction(1.4, 0.5); -> 1.5
> round2fraction(1.8, 0.5); -> 2.0
> round2fraction(1.0, 0.5); -> 1.0
> round2fraction(1.25, 0.5); -> 1.5
> round2fraction(-1.6, 0.5); -> -1.5
>
> We have here a private implementation, but this is probably not as
> optimised
> as those numerical guru's can come up with. Is this a good suggestion to
> add
> to Boost.Math or overkill?

Probably overkill to add to Boost.Math, but how about:

template <class T>
T round2fraction(T x, T f)
{
   return f * round(x/f);
}

where "round" is either the C99 one or the boost::math:: one if you need
something more generic.

Of course this assumes that parameter "f" is exactly representable as a
floating point value, in fact it might need to be a power of 2 in order to
be certain of being completely safe and accurate....

HTH, John.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net