logankilpatrick
logankilpatrick

Reputation: 14521

How to check if two arrays are equal even if they contain NaN values in Julia?

I am trying to compare two arrays. It just so happens that the data for the arrays contains NaN values and when you compare arrays with NaN values, the results are not what I would have expected.

julia> a = [1,2, NaN]
3-element Array{Float64,1}:
   1.0
   2.0
 NaN  

julia> b = [1,2, NaN]
3-element Array{Float64,1}:
   1.0
   2.0
 NaN  

julia> a == b
false

Is there an elegant way to ignore these Nan's during comparison or replace them efficiently?

Upvotes: 14

Views: 1897

Answers (4)

Kristoffer Carlsson
Kristoffer Carlsson

Reputation: 2838

You probably want to use isequal(a, b) (which also treats missing equal to missing, but -0.0 as unequal to 0.0).

Upvotes: 3

giordano
giordano

Reputation: 8344

Use isequal:

Similar to ==, except for the treatment of floating point numbers and of missing values. isequal treats all floating-point NaN values as equal to each other, treats -0.0 as unequal to 0.0, and missing as equal to missing. Always returns a Bool value.

julia> a = [1,2, NaN]
3-element Array{Float64,1}:
   1.0
   2.0
 NaN  

julia> b = [1,2, NaN]
3-element Array{Float64,1}:
   1.0
   2.0
 NaN  

julia> isequal(a, b)
true

Upvotes: 18

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

Or create a new type. And create a Singleton nan which you use instead of NaN.

struct MyNaN end
nan = MyNaN()

and write a function for replacing NaNs by it.

with_nan(l) = map((x) -> if isnan(x) nan else x end, l)

Then you can wrap your lists using this function.

a = [1, 2, NaN]
b = [1, 2, NaN]
with_nan(a) == with_nan(b)
## true

Upvotes: 1

Luan Nico
Luan Nico

Reputation: 5917

You could filter out the NaN's on each array:

a = [1, 2, NaN]
filteredA = filter(x -> !isnan(x), a)

b = [1, 2, NaN]
filteredB = filter(x -> !isnan(x), b)

print(a == b)
print(filteredA == filteredB)

You could then create a function that does the filtering, and a custom compare function that uses the filtering function on both arguments and compare. Not sure if there is a more Julia-esque way.

Upvotes: 1

Related Questions