2

For example:

scala> val my_array = Array(4,5,Double.NaN,6,5,6, Double.NaN)
my_array: Array[Double] = Array(4.0, 5.0, NaN, 6.0, 5.0, 6.0, NaN)

scala> my_array.count(_ == Double.NaN)
res13: Int = 0

I understand that two Double.NaN are not equal to each other

scala> Double.NaN == Double.NaN
res14: Boolean = false

and therefore, I get the result that I get, but I can't find a function that would tell me the number of Double.NaNs, what am I missing?

In python the behaviour would look like this:

In [43]: import numpy as np

In [44]: a = np.array([5,np.nan,5,7,4,np.nan])

In [45]: np.isnan(a)
Out[45]: array([False,  True, False, False, False,  True], dtype=bool)

In [46]: np.isnan(a).sum()
Out[46]: 2
Akavall
  • 82,592
  • 51
  • 207
  • 251
  • possible duplicate of [In Scala, why is NaN not being picked up by pattern matching?](http://stackoverflow.com/questions/6908252/in-scala-why-is-nan-not-being-picked-up-by-pattern-matching) – Justin Pihony May 15 '15 at 21:33
  • I don't think my question is a duplicate, that question is asking mostly about why `NaN`s are not equal to each other. I already knew it, I just needed a function to deal with it. – Akavall May 15 '15 at 21:43
  • OK, I guess I had assumed you could change your count to do an isNan instead of an == ...... – Justin Pihony May 15 '15 at 21:55
  • 1
    As for _why_, it's IEEE-754 standard floating point behavior, enshrined in CPUs since the 1980's. I believe it was done so that a quick test for NaN could be done with no addition instruction opcodes by testing for (x==x). If it's false, it isn't a number - it's a NaN. – Ed Staub May 16 '15 at 03:01

1 Answers1

4

Double.isNan does the job:

scala> val array = Array(4,5,Double.NaN,6,5,6, Double.NaN)
array: Array[Double] = Array(4.0, 5.0, NaN, 6.0, 5.0, 6.0, NaN)

scala> array.count(_.isNaN)
res0: Int = 2
Infinity
  • 3,431
  • 3
  • 25
  • 46