0

Hi I am wondering why findall function doesnt seem to work at times. Here is an example

m = rand(9) |> x -> reshape(x, (3,3))
#3×3 Matrix{Float64}:
# 0.560603  0.415519  0.901541
# 0.978412  0.807979  0.945599
# 0.544259  0.645748  0.16898

findall(x -> x == 0.560603, m)
# CartesianIndex{2}[]

However when I do this, it seems to work

m2 = Matrix([1.6549 18.85849 90.8493 ; 2.339490 6.83490 8.1392])
findall(x -> x == 8.1392, m2)

#1-element Vector{CartesianIndex{2}}:
#CartesianIndex(2, 3)

Any idea's why?

imantha
  • 2,676
  • 4
  • 23
  • 46
  • 1
    Floating point precision issues. Use `isapprox()` not `==` for non-integer numerics. – Gregor Thomas Oct 27 '22 at 13:34
  • Does this answer your question? [Julia:How to deal with precision exactness in floating points](https://stackoverflow.com/questions/46077127/juliahow-to-deal-with-precision-exactness-in-floating-points) – Gregor Thomas Oct 27 '22 at 13:34
  • See [How to deal with precision exactness in floating points?](https://stackoverflow.com/q/46077127/903061), or [Unexpected behavior in boolean comparison](https://stackoverflow.com/q/48591515/903061), or the language-agnostic [Is floating point math broken?](https://stackoverflow.com/q/588004/903061) – Gregor Thomas Oct 27 '22 at 13:36
  • Does this answer your question? [julia floating point compare for zero](https://stackoverflow.com/questions/44959030/julia-floating-point-compare-for-zero) – Andre Wildberg Oct 27 '22 at 13:55
  • `isapprox` will almost certainly not work here, at least with default settings. This isn't a float precision issue, but a _printing_ precision issue. – DNF Oct 27 '22 at 14:08

1 Answers1

3

There's nothing wrong with findall, at least in your case.

Your problem is that there are no elements with value 0.560603 in your matrix. Here's an example:

julia> m = rand(3, 3)  # no need to do rand(9) |> reshape
3×3 Matrix{Float64}:
 0.972025  0.985549  0.567716
 0.175912  0.311136  0.584218
 0.23278   0.148898  0.0805185

julia> m[3, 1] == 0.23278
false

julia> m[3, 1] ≈ 0.23278  # isapprox doesn't work either
false

Why is this? It's a printing issue, here you can see it with full precision:

julia> m[3, 1]
0.232779977510291

This works:

julia> findall(==(0.232779977510291), m)
1-element Vector{CartesianIndex{2}}:
 CartesianIndex(3, 1)

The comments are still right in that you should be careful about doing exact floating point comparison.

DNF
  • 11,584
  • 1
  • 26
  • 40