1
$\begingroup$

I dfined the following function to create a pattern that matches the $\epsilon$-neighborhood of a given number.

ep[x_, e_] := _?(x - e <= # <= x + e &)

So, for example, the pattern ep[10.4, 10^-2] matches all numbers $x$ such that $|x-10.4| < 0.01$.

I am wondering if there is a simpler, more readable way of expressing this, not involving an intermediate function definition.

$\endgroup$
  • $\begingroup$ You could use Condition instead of PatternTest. Whether this is simpler or more readable is probably a matter of perspective, though. $\endgroup$ – Oleksandr R. Jan 15 '16 at 13:35
2
$\begingroup$

Are you looking for a shorter function to create a pattern? Or just a way to write the pattern without a function? Your function could be shorter by writing

ep[x_, e_] := _?(Abs[x - #] <= e &)


lst = 10.4 + RandomReal[{-.02, .02}, 10]
Cases[lst, ep[10.4, 10.^-2]]
Cases[lst, _?(Abs[10.4 - #] <= .01 &)]
(* {10.4099, 10.4196, 10.3874, 10.3976, 10.3844, 10.4185, 
    10.3985, 10.3892, 10.3946, 10.4122} *)
(* {10.4099, 10.3976, 10.3985, 10.3946} *)
(* {10.4099, 10.3976, 10.3985, 10.3946} *)

Or a little longer, but perhaps more readable,

ep[x_, e_] := _?(LessEqualThan[e][Abs[x - #]] &)

Of course, that's if you want to use Cases. You could use Select in which case the syntax is a little shorter,

Select[lst, (Abs[10.4 - #] <= .01 &)]
(* {10.4099, 10.3976, 10.3985, 10.3946} *)
$\endgroup$

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.