How can one find the closest larger and closest smaller number from a maxima list? Which maxima functions should I explore?
Asked
Active
Viewed 66 times
1
-
Not sure what you mean. Maybe you mean `ceiling` and `floor`. Or maybe you mean `sort(mylist);` and then look at `mylist[k + 1]` and `mylist[k - 1]` for any element `k`. – Robert Dodier Nov 29 '21 at 19:17
-
e.g. ```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];``` and ```x : 0.04;``` the closest smaller than '''x''' is 0.028 and closest larger is 0.056. Which function can let me automate this search? – mily Nov 30 '21 at 06:19
1 Answers
0
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.

Robert Dodier
- 16,905
- 2
- 31
- 48