title: Replacing a for loop in python by array slicing and numpy.diff when step size is larger than 1
body: <p>I want to calculate the derivative via finite differences, note though that I have a stepsize of 2 grid points here.</p>
  <p>This can be easily realized in a <code>for</code> loop, which is however quite slow. Since I am working on <code>numpy</code> arrays, I replaced the <code>for</code> loop by array slicing to get a significant speed up. Then I wanted to test/compare <code>numpy.diff</code> but I get a different result using it.</p>
  <pre><code>import matplotlib.pyplot as plt
  import numpy as np
  
  # create some data
  n   = 100
  x   = np.linspace(0,2*np.pi,n)
  y   = np.linspace(0,2*np.pi,n)
  X,Y = np.meshgrid(x,y)
  Z   = np.sin(X) * np.sin(Y)
  
  # calculate centered finite difference using for loop
  Z_diff1 = Z*.0
  for ii in range(1,Z.shape[0]-1,2):
      for jj in range(1,Z.shape[1]-1,2):
          Z_diff1[ii,jj]  = Z[ii-1, jj] - Z[ii+1,jj]
  
  # calculate centered finite difference using array slicing
  Z_diff2 = Z[:-2:2,::2] - Z[2::2,::2]
  
  # calculate centered finite difference using numpy.diff
  Z_diff3 = np.diff(Z[::2,::2], axis=0)
  
  fig = plt.figure( figsize=(8,6) )
  
  ax1 = fig.add_subplot( 1,4,1, aspect='equal' )
  ax1.pcolormesh(Z)
  ax1.set_title('original data')
  
  ax2 = fig.add_subplot( 1,4,2, aspect='equal' )
  ax2.pcolormesh(Z_diff1[1::2,1::2])
  ax2.set_title('for loops')
  
  ax3 = fig.add_subplot( 1,4,3, aspect='equal' )
  ax3.pcolormesh(Z_diff2)
  ax3.set_title('slicing')
  
  ax4 = fig.add_subplot( 1,4,4, aspect='equal' )
  ax4.pcolormesh(Z_diff3)
  ax4.set_title('numpy.diff')
  
  plt.show()
  </code></pre>
  <p>As can be seen from the figure, the result from <code>numpy.diff</code> looks different - what am I missing here?</p>
  <p><a href="https://i.stack.imgur.com/4auRX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4auRX.png" alt="enter image description here" /></a></p>