6

Bug introduced in 10.0 and fixed in 10.1


MovingMap (new in version 10) applies a function to discrete data over a moving window. This is very convenient for calculating the percentage change of a series.

But the error returned by the following code bothers me:

series = Range[5];
MovingMap[#[[2]]/#[[1]] - 1 &, series, {2}]

(* Power::infy: Infinite expression 1/0. encountered. >>\*)
(* {1, 1/2, 1/3, 1/4} *)

However, this code returns the result with no error:

MovingMap[f, series, {2}] /. f -> Function[#[[2]]/#[[1]] - 1]

(* {1, 1/2, 1/3, 1/4} *)

What causes this problem?

dr.blochwave
  • 8,768
  • 3
  • 42
  • 76
Y. Kwon
  • 565
  • 2
  • 8

2 Answers2

6

Update

In version 10.1 the overhang problem described below has been removed. (In the default form; with Method -> "Legacy" the behavior below returns.) I am therefore tagging this as a bug.

Beware that MovingMap syntax has incompatibly changed in 10.1 as well.


This appears to be a bug in MovingMap. The function is applied beyond the left edge of the list and then the result is discarded:

echo[x_] := (Print[x]; x)

MovingMap[echo, Range@5, {2}]

{0,1}

{1,2}

{2,3}

{3,4}

{4,5}

{{1, 2}, {2, 3}, {3, 4}, {4, 5}}

I can see no reason to use the padding element 0 here. Interestingly when one specifies a different padding element that first result is not discarded:

MovingMap[Identity, Range@5, {2}, foo]
{{foo, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}}

The documentation for the padding parameter is:

enter image description here

So supposedly the default is no padding, but that is not true; the default padding is 0, and then the result is discarded. Again:

MovingMap[echo, Range@5, {5}]

{0,0,0,0,1}

{0,0,0,1,2}

{0,0,1,2,3}

{0,1,2,3,4}

{1,2,3,4,5}

{{1, 2, 3, 4, 5}}

There is no reason for the function (echo) to be applied the first four times, and in fact this directly contradicts the documentation which states that "no padding" is the default.

Also weird is this case:

MovingMap[echo, Range@5, {5, 2}]

{0,0,0,0,1}

{0,0,0,1,3}

{0,0,1,3,5}

MovingMap[echo, {1, 2, 3, 4, 5}, {5, 2}]

So even though it appears that the parameters are invalid and the entire MovingMap expression is returned unevaluated, the echo function is still applied to three times.

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2

IMHO this is a Bug. You can prevent the error message in V10 using Quiet:

series = Range[5];
MovingMap[Quiet[#[[2]]/#[[1]] - 1 &], series, {2}]

You can also use Internal`PartitionMap, without Quiet:

Developer`PartitionMap[#[[2]]/#[[1]]-1&, Range@5, 2, 1]

{1,1/2,1/3,1/4}

Post about PartitionMap

UPDATE

Fixed in 10.1

Murta
  • 26,275
  • 6
  • 76
  • 166