Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to determine if a particular arithmetic operation has caused an overflow

I've a feeling that this might not be possible, but in case any one has any ideas, it would be of great help. For any floating point arithmetic operation, is it possible to determine that the operation caused a precision loss. e.g if i calculate z = x/y, I want to determine if z has the exact value or if some precision has been lost during the operation.

Why I need this: I am doing some mathematical operations using interval arithmetic. If the result is not precise I need to return a range where the exact result lies in the form of [a,b]. Currently for every operation I am assuming a precision loss. If the result is x, I return [previousClosestFPNumber(x), nextClosestFPNumber(x)]. This works flawlessly. However for very complicated equations the range becomes too large. If I can determine that precision has been lost, I can only widen the range in that case.

like image 948
v1p3r Avatar asked Oct 25 '25 15:10

v1p3r


1 Answers

If you're losing precision in the operation f(x), then it should be detectable by applying the inverse operation to the result and seeing if you get back something other than the original value: in mathematical parlance, f'(f(x)) != x.

For example, something like:

x = y * z
y2 = x / z
if y != y2: precision was lost

If that turns out not to be suitable, you may want to consider a bignum library where you don't lose precision, such as javascript-bignum (though I'm sure there would be others around as well).

like image 86
paxdiablo Avatar answered Oct 27 '25 05:10

paxdiablo