
Dear all, I implemented a simple function to differentiate an array which seems other people might like to have. It looks like: def diff(f, x, retval = 'same'): """ Differentiate f w.r.t. x and return the diff with same samples, or different depending on retval. retval can be: same: return data for same data points as the indata. This is done through interpolation at internal points and extrapolation at endpoint simple: just return the scaled diff samesimple: return with same size vector, just shifted. Last data point is repeated. new: return at new datapoints and length - 1 """ df = f[1:] - f[:-1] dx = x[1:] - x[:-1] dfodx = df/dx if retval == 'new': return dfodx, x[:-1] + dx/2 elif retval == 'same': cdfodx = np.zeros(len(f)) cdfodx[1:-1] = (dfodx[:-1] + dfodx[1:])/2 cdfodx[0] = dfodx[0]-0.5*(dfodx[1] - dfodx[0])/dx[0] cdfodx[-1] = dfodx[-1]+0.5*(dfodx[-1] - dfodx[-2])/dx[-1] return cdfodx, x elif retval == 'simple': return dfodx, x[:-1] elif retval == 'samesimple': cdfodx = np.zeros(len(f)) cdfodx[:-1] = dfodx cdfodx[-1] = dfodx[-1] return cdfodx, x And generates the following results (top plot original function, bottom different differentiates) from the code blow: x = np.linspace(0,2*np.pi,10) f = np.sin(x) plt.subplot(211) plt.plot(x, f, marker="*") plt.ylabel('$\sin(y)$') plt.grid(True) plt.subplot(212) df,xp = diff(f, x, 'simple') plt.plot(xp, df, marker="*", label='simple', linewidth=4) df,xp = diff(f, x, 'new') plt.plot(xp, df, marker="*", label='new') df,xp = diff(f, x, 'same') plt.plot(xp, df, marker="*", label='same') df,xp = diff(f, x, 'samesimple') plt.plot(xp, df, marker="*", label='samesimple') plt.ylabel('$d\sin(x)/dx$') plt.xlabel('$x$') plt.grid(True) plt.legend(loc='lower right') What do you think about adding it to scipy? Best, Robert