Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double overflow [duplicate]

Tags:

c#

.net

I have some problems with double type. At MSDN i read about double max value following:

The result of an operation that exceeds Double.MaxValue is Double.PositiveInfinity.

I wrote some tests:

Console.WriteLine(double.MaxValue + 100000 - double.MaxValue);
Console.WriteLine(double.MaxValue);
Console.WriteLine(double.MaxValue + 100000);
Console.WriteLine(double.IsPositiveInfinity(double.MaxValue + 100000));

And saw this result:

0
1,79769313486232E+308
1,79769313486232E+308
False

I don't understand, double.MaxValue + 100000 isn't Positive infinity, but equal to double MaxValue. I think it should be PositiveInfinity, according to msdn documentation.

I tested it in VS2012, .NET 4.5

like image 227
Sergey Popov Avatar asked Dec 04 '13 08:12

Sergey Popov


1 Answers

This is rounding / precision; from the perspective of a number that is 309 digits long (before the decimal place), 100000 is essentially zero. You might as well add 0.

If you try double.MaxValue * 2 - i.e. something that will actually be noticeable to it, then it will show as positive infinity.

like image 54
Marc Gravell Avatar answered Nov 11 '22 02:11

Marc Gravell