From: Andy Little (andy_at_[hidden])
Date: 2005-04-02 03:48:15
"Peter Dimov" <pdimov_at_[hidden]> wrote in message
> Jonathan Turkanis wrote:
>> No, I was claiming that in some cases a developer might know the
>> range of all possible inputs, and be able to reason that no overflow
>> could occur.
> You do understand that the range of the inputs has almost nothing to do with
> overflow, right?
There is a safe range of values for each operation.
eg for an implementation of rational addition where Rationalx = Nx/ Dx
and operator + is implemented as :
(N1 * D2 + N2 * D1 ) "/ "(D1 * D2)
Assuming the same maximaum allowable value for each of N1, D1, N2, D2
max value of ( N1 * D2 + N2 * D1) occurs when
N1 == D1 == D2 == N2,
max value of (D1 *D2) when D1 == D2,
therefore max allowable value of all these is:
For a 16bit int this leaves you with a safe range of +-127 in this case.Of
course after 'normalisation' referred to in the boost::rational docs, the result
of the addition itself may or may not be out of range.
boost::rational uses a more complicated algorithm for addition, but nevertheless
the above limit algoritm(which might be improved upon of course) holds I think.
I would guess that the limit would need to be 'implementation defined', but
(ideally) available as part of rationals interface. The alternative is to simply
do the calculation but perhaps then the algorithm used in boost::rational leads
to a very unpredictable set of valid numerator ,denominator values per operand
per operation, which is not very satisfactory from a users viewpoint. Perhaps
both the safe contiguous range and the 'feeling lucky' range could be made
available, though one of these would probably not be much used !
Incidentally similar,solvable problems occur in integer
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk