# Pattern that matches numbers in the $\epsilon$-neighborhood of a given number?

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.

• You could use Condition instead of PatternTest. Whether this is simpler or more readable is probably a matter of perspective, though. Jan 15, 2016 at 13:35

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} *)