How can one find the closest larger and closest smaller number from a maxima list? Which maxima functions should I explore?
Here's a solution based on finding the sublist of elements which are less than or greater than x
, and returning the greatest or least such element. If there is no such element, false
is returned.
(%i4) next_smaller (L, x) :=
(sort(L),
sublist (%%, lambda ([y], y < x)),
if %% # [] then last(%%)) $
(%i5) next_larger (L, x) :=
(sort(L),
sublist (%%, lambda ([y], y > x)),
if %% # [] then first(%%)) $
(%i6) list: [0, 0.014, 0.021, 0.028, 0.042, 0.056, 0.07, 0.084, 0.11, 0.17, 0.28, 0.42, 0.56] $
(%i7) next_smaller (list, 0.04);
(%o7) 0.028
(%i8) next_larger (list, 0.04);
(%o8) 0.042
(%i9) next_larger (list, 0.56);
(%o9) false
(%i10) next_smaller (list, 0.56);
(%o10) 0.42
(%i11) next_smaller (list, 0);
(%o11) false
(%i12) next_larger (list, 0);
(%o12) 0.014
(%i13) next_larger (list, -1);
(%o13) 0
(%i14) next_smaller (list, -1);
(%o14) false
(%i15) next_smaller (list, 1);
(%o15) 0.56
(%i16) next_larger (list, 1);
(%o16) false
These functions probably could be made more efficient, but you might notice the difference only if you're working with long lists. Maybe see if this works before trying to optimize.