1
$\begingroup$

Reading the documentation of Position, I found there's a possible issue:
Position looks for matches based on patterns, which may not be the same as numerical equality:

Position[Range[-1, 1, 0.05], 0.1]
{} 

Then a possible way to fix this is left

Position[Range[-1, 1, 0.05], n_ /; n == 0.1]
{{23}}

My question: Is there a way to fix this issue when you have a list of lists? Because I tried something like the above and it didn't work.

$\endgroup$
2
  • $\begingroup$ Let me know if I didn't explain it well. $\endgroup$ Aug 11 '18 at 5:11
  • 1
    $\begingroup$ You should give an example of "I tried something like the above and it didn't work" because it should work, e.g. Position[{{1., 2., 3.}, {4., 5., 6.}}, n_ /; n == 5] $\endgroup$
    – Mr.Wizard
    Aug 11 '18 at 5:37
2
$\begingroup$

If you want equality, use rational numbers rather than floating point:

Position[Range[-1, 1, 1/20], 1/10]
{{23}}
$\endgroup$
2
$\begingroup$

You can use

Nearest[Range[-1, 1, 0.05] -> "Index", 0.1]

{23}

Alternatively,

Position[Chop[Range[-1, 1, 0.05] - .1], 0] (* or *)
Position[Round[Range[-1, 1, 0.05], .05], 0.1]

{{23}}

If you check the FullForm of Range[-1, 1, 0.05] you see that it doesn't contain 0.1:

Range[-1, 1, 0.05] // FullForm

enter image description here

$\endgroup$
2
  • $\begingroup$ Might I ask why the heck it doesn't contain 0.1? It would seem logical that it should. $\endgroup$
    – Emy
    Aug 13 '18 at 6:57
  • $\begingroup$ @Emy, not sure exactly why. $\endgroup$
    – kglr
    Aug 14 '18 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.