allclose - How to check if two arrays are close in Julia

julia, numpy

Solution

(For the obsolete version of this answer, see below the horizontal line.)

An array version of `isapprox` was introduced in Julia 0.4, so you can now write:

isapprox(A, B)

Like in the scalar case, you can specify the relative tolerance `rtol` and the absolute tolerance `atol` as keyword arguments.

But note that unlike NumPy's `allclose` (and the previous solution of this answer below), array-`isapprox` calculates a norm of the difference first, and then decides for the resulting value. (Appearently, checking `isapprox` pointwise is wrong.) By default, `LinearAlgebra.norm` is used, which is the 2-norm for vectors and the Froebenius norm for matrices, but you can override this behavior using the `norm` keyword argument.

By the way, as mentioned in the linked pull request, in tests you can write `@test isapprox(A, B)`, so `@test_approx_eq` is now obsolete and deprecated as of 0.6. Also, there is `A ≈ B`, which is equivalent to `isapprox(A, B)` and can be used like any comparison operator: `a < b ≈ c ≤ d`.

For reference, this is the previous, outdated version of this post:

For single numbers, `isapprox` is defined. If you want to extend this to an element-wise comparison on `Array`s, you could use:

all(x -> isapprox(x...), zip(A, B))

all(x -> isapprox(x...), zip(A, A + 1e-5)) # => false
all(x -> isapprox(x...), zip(A, A + 1e-6)) # => true

Problem

In numpy you can do `np.allclose(A, B)` to see if the arrays A & B are close. Is there any function in Julia to do so ?

Original source