Jiyoon Go
Jiyoon Go

Reputation: 59

In R, why does is.numeric(NaN) print "TRUE"?

NaN` means "Not a Number". However I found out that the result of

is.numeric(NaN)

is

[1] "TRUE"

Anybody know why? I think the result should be FALSE.

Upvotes: 2

Views: 813

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73285

"Not a Number" does not really mean it is not a number. It is a special coding of a floating-point number. See ANSI/IEEE 754 floating-point standard, or simply the Wikipedia page for NaN.

This is a universal standard for all computing languages and R's handling is no exception.

In R, typeof(NaN) gives "double", and mode(NaN) gives "numeric". Now if you read ?is.numeric, you see that is.numeric(x) returns TRUE if x has mode "numeric" and is not a factor.

The IEEE standard defines three special floating-point numbers, Inf, -Inf and NaN.

The first two have a clear mathematical meaning: positive infinite and negative infinite. Although they are not part of real number, they are well-defined limit. For example, 1 / 0 is Inf.

So what does NaN mean? Precisely it is not well-defined real number. Simple cases are

0 / 0  # can be either Inf or -Inf
sqrt(-1)  # not well-defined on real number set
Inf - Inf  # can not be decided, can be 0, Inf or -Inf

In numerical computing, if the result can not be written in regular real number, or Inf or -Inf, it is expressed as NaN. In this regard, arithmetics between any floating-point numbers becomes completely representable. NaN is quite informative in this regard, it means "something has gone wrong".


Note that unlike NA which has various types (NA_real_, NA_integer_, etc), NaN has only one type for floating-point numbers. Any logical, character, integer values are not floating-point numbers hence can not be NaN. The definition of NA is not a universal standard and R has its own.

Upvotes: 3

Related Questions