Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (int)double.NaN and (int)double.PositiveInfinity are 0?

Tags:

in C#, if you 0/0 you get an exception.

But if you 0.0/0 or 0.0/0.0 you get double.NaN and double.Infinity, respectively.

but if you cast these results to int, you get 0.

> (int)double.PositiveInfinity 0 > (int)double.NaN 0 

Why is this the case? Isn't the runtime supposed to give casting error because infinity is clearly not a zero?

like image 389
ahmet alp balkan Avatar asked Jan 09 '13 19:01

ahmet alp balkan


People also ask

What is NaN double C#?

The Double. IsNaN() method in C# is used to return a value that indicates whether the specified value is not a number (NaN).

What is the difference between NaN and infinity?

In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself.

What is NaN in VB net?

A method or operator returns NaN when the result of an operation is undefined. For example, the result of dividing zero by zero is NaN, as the following example shows. (But note that dividing a non-zero number by zero returns either PositiveInfinity or NegativeInfinity, depending on the sign of the divisor.)


1 Answers

It depends on what kind of context you're in. If you use a checked context, you'll get an exception. The relevant section of the spec is section 6.2.1:

For a conversion from float or double to an integral type, the processing depends on the overflow checking context (§7.6.12) in which the conversion takes place:

  • In a checked context, the conversion proceeds as follows:
    • If the value of the operand is NaN or infinite, a System.OverflowException is thrown.
    • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
    • Otherwise, a System.OverflowException is thrown.
  • In an unchecked context, the conversion always succeeds, and proceeds as follows.
    • If the value of the operand is NaN or infinite, the result of the conversion is an unspecified value of the destination type.
    • Otherwise, the source operand is rounded towards zero to the nearest integral value. If this integral value is within the range of the destination type then this value is the result of the conversion.
    • Otherwise, the result of the conversion is an unspecified value of the destination type.

So in an unchecked context, the answer isn't necessarily 0 - it's an unspecified int value. In fact, in my testing, it comes up as int.MinValue rather than 0 in an unchecked context.

But fundamentally, if you want to do checking, use a checked context (at least for that expression).

like image 56
Jon Skeet Avatar answered Oct 28 '22 09:10

Jon Skeet