Arrays to vector conversion

Using isapprox elementwise is often a bad idea. For example:

julia> isapprox([1, 0], [1, 1e-16])
true

julia> all(isapprox.([1, 0], [1, 1e-16]))
false

1e-16 ≈ 0 is false, and rightly so, because the two numbers have no significant digits in common, and there is no reference by which to set an absolute scale. (You don’t know the “units”. See also the isapprox documentation on why the default tolerance is relative error, not absolute error.)

The advantage of applying isapprox to the whole array at once is that the norm of the whole array sets an overall scale with which to compare the elements: 1e-16 - 0 is small compared to the norm ≈ 1, so [1,0] ≈ [1,1e-16] rightly returns true.

Approximate comparison is one of those things that’s really easy to get wrong, unfortunately. (e.g. numpy.isclose got it wrong.)

PS. I think “non-allocating” here is probably an irrelevant metric. isapprox is not something that you usually do in performance-critical settings.

4 Likes