Dumbledore
Dumbledore

Reputation: 460

Why doesn't adding a number to Double.MaxValue makes it Double.PositiveInfinity?

In Double.PositiveInfinity docs it's written that:

This constant is returned when the result of an operation is greater than MaxValue.

However, when I try to add a number to maximum value of double, it doesn't return infinity. I've tried running this:

double maxVal = Double.MaxValue;
maxVal = maxVal + 10000000000000000000;
Console.WriteLine(maxVal + " " + Double.IsInfinity(maxVal)); //prints 1.79769313486232E+308 False

Why is it happening? Why isn't it showing maxVal as infinity?

Here is a working fiddle.

Upvotes: 9

Views: 2094

Answers (2)

Bellash
Bellash

Reputation: 8184

(*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;

When you substitute it in your example, then you will see that double.MaxValue which value is 1.7976931348623157E+308 + 10000000000000000000 is still smallest than 0x7FF0000000000000 after conversion.

  • Why does it return double.MaxValue, because, as per math definition, X+z=X for very greater values of X and smallest of z.

Upvotes: 0

Guffa
Guffa

Reputation: 700302

That's because the number that you are adding is way too small to make a dent on the Double.MaxValue value.

The precision of a double is about 15 digits, so you need a number that is at least 1e292 for it to be large enough to make a difference.

That would be 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 written out.

Upvotes: 12

Related Questions