How do you know if the sum of two double's will give greater than the limit of a double?

8

Is there any way to know if a sum between two values in the format double will exceed the limit of the variable double ?

Example with integer: 2147483648 + 1. In this case it goes beyond the limit of an integer, I do not know if it would give an exception or if it would be negative.

    
asked by anonymous 19.10.2016 / 10:40

1 answer

7

Normally, if you exceed the limit of as many as possible on the type it turns and start again at the lowest possible number of the type, then the integer would be negative.

Unless you ask the operation to be checked. Then an exception would be generated. I answered about this in What is checked in C # code? .

All numeric types of .Net have a constant indicating the largest and smallest number possible. So to check if an entire will burst need to buy from them. Something like this:

if (x <= Int32.MaxValue - y) {
    z = x + y;
}

Just remembering that if this value is in some shared object and can be accessed concurrently in different threads there may be a Race condition . For this there is checked . In such situation it is better to do the operation and check if the account went wrong by catching the exception.

In the case of type double it is more complicated and has the method Double.IsPositiveInfinity() " to verify that the value "broke". There are other techniques, but I believe this is the most reliable. Given the non-exact nature of the type there are no warranties.

var x = Double.MaxValue;
double y = 0;
if (!Double.IsPositiveInfinity(x * 2)) {
    y = x * 2;
}

See working on dotNetFiddle and on repl.it .

    
19.10.2016 / 11:32