3
$\begingroup$

If I have a list:

{a,b,c,d,e,f}

Is there a function that allows me to easily construct a list that shows the intervals between elements:

{b-a,c-b,d-c,e-d,f-e}

I know I can shift the list then subtract (like below), but I am not sure whether there is a single function that would allow me to do it:

{a,b,c,d,e,f,0}-{0,a,b,c,d,e,f}

Thanks.

$\endgroup$
  • 6
    $\begingroup$ Use Differences $\endgroup$ – MarcoB May 6 at 15:17
  • $\begingroup$ Awesome! Thanks! $\endgroup$ – baker May 6 at 15:19
  • $\begingroup$ Differences[L] is fine, as @MarcoB says; but for top speed I was surprised to find that Rest[L]-Most[L] is a bit faster. $\endgroup$ – Roman May 6 at 15:58
4
$\begingroup$

As @MarcoB says, Differences is the canonical way to go:

L = Sort@RandomReal[{0, 1}, 10^7];
d1 = Differences[L]; // RepeatedTiming // First
(* 0.20 *)

Rest-Most is twice as fast though, which I find very strange:

d2 = Rest[L] - Most[L]; // RepeatedTiming // First
(* 0.090 *)

BlockMap is a terrible idea:

d3 = BlockMap[#[[2]] - #[[1]] &, L, 2, 1]; // RepeatedTiming // First
(* 4.60 *)

All methods agree on the result though:

d1 == d2 == d3
(* True *)
$\endgroup$
  • 2
    $\begingroup$ The nice thing about Differences is the ease in using the second parameter to get differences of differences, and so on (wonder if the Rest/Most approach still holds out as better in that case). $\endgroup$ – MikeY May 6 at 18:59
  • 2
    $\begingroup$ @MikeY yes it's still faster: Differences[L, 2] takes 0.36 seconds and L[[3 ;;]] + L[[;; -3]] - 2 L[[2 ;; -2]] takes only 0.25 seconds. $\endgroup$ – Roman May 6 at 20:03

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