How do I know that the sum of two double’s will be greater than the limit of one double?

Asked

Viewed 273 times

9

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

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

1 answer

8


The normal is if you exceed the limit of the maximum possible number in the type it turns and start again in the smallest possible number of the type, then the integer would be negative.

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

All numeric types of . NET have a constant indicating the largest and smallest possible number. So to check if a whole will burst need to buy with 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 threads there may be a running condition. For that there is the checked. In such a situation it is better to do the operation and check if the account went wrong by catching the exception.

In the case of the type double is more complicated and has the method Double.IsPositiveInfinity() to check if the value "exceeded". There are other techniques, but I believe this is the most reliable. Given the non-exhaustive nature of the type there are no guarantees.

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

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.