What are the benefits of NaN
, PositiveInfinity
or NegativeInfinity
for float
and double
? When should we use or avoid them?
If there are constants like these, why does float.Parse("a")
throw an error rather than returning float.NaN
?
How is NaN
different than null
? Why is division by zero
even possible for floating types?
Infinities are used because they are part of the arithmetic system supported by floating point. There are various operations, such as dividing by zero, in which infinity is a useful result and is mathematically sensible. Obviously, no direct physical quantity can be infinite (you cannot have infinitely many grams, for example), but infinity may be a useful value for some aspect of a mathematical model of physical processes or other things that humans model with computers.
NaNs are used because the arithmetic system is incomplete. That is, there are operations with input values for which the proper mathematical result is not representable within floating point. For example, sqrt(-1) is a legitimate mathematical operation, but the result, the imaginary number i, is not representable in floating point. So NaN is used as a placeholder to indicate that the values have gone outside the floating point numbers. NaN can also be used for other purposes, such as marking data that is not otherwise initialized, to help with debugging.
float.Parse("a")
throws an error rather than returning a NaN because it is a not a legitimate operation. This expression does not perform a mathematical operation that has a proper result outside the representable numbers. It is an actual error, so it throws an error.