TimeSeriesDifferencing { public static double[] differencesAtLag(double[] x, int differences) { if (differences < 1) { throw new IllegalArgumentException("Differences should be > 0"); } if (x == null || x.length <= differences) { throw new IllegalArgumentException("Not enough values for differencing"); } double[] temp = Arrays.copyOf(x, x.length); for (int i = 0; i < differences; i++) { firstDifferences(temp); } return Arrays.copyOfRange(temp, 0, x.length - differences); } private  TimeSeriesDifferencing(); static double[] differencesAtLag(double[] x, int differences);  }
@Test public void testDiff() throws Exception { double[] x = { 1, 11, 3, 5, 8 }; double[] expected1 = { 10, -8, 2, 3 }; double[] expected2 = { -18, 10, 1 } ; double[] diff1 = TimeSeriesDifferencing.differencesAtLag(x, 1); double[] diff2 = TimeSeriesDifferencing.differencesAtLag(x, 2); Assert.assertEquals(x.length - 1, diff1.length); Assert.assertArrayEquals(expected1, diff1, 0.00001); Assert.assertArrayEquals(expected2, diff2, 0.00001); }
@Test public void testErrorStates() { try { TimeSeriesDifferencing.differencesAtLag(new double[0], 0); Assert.fail(); } catch (IllegalArgumentException ex) { } try { double[] diff = TimeSeriesDifferencing.differencesAtLag(new double[]{1}, 1); Assert.fail(); } catch (IllegalArgumentException ex) { } try { double[] diff = TimeSeriesDifferencing.differencesAtLag(new double[]{1, 3, 2}, 3); Assert.fail(); } catch (IllegalArgumentException ex) { } }