# [Scipy-tickets] [SciPy] #564: Change derivative() to return the gradient of multidimensional functions

SciPy scipy-tickets@scipy....
Mon Dec 17 09:16:39 CST 2007

```#564: Change derivative() to return the gradient of multidimensional functions
-------------------------+--------------------------------------------------
Reporter:  robfalck     |        Owner:  jarrod.millman
Type:  enhancement  |       Status:  new
Priority:  normal       |    Milestone:  0.7
Component:  scipy.misc   |      Version:
Severity:  minor        |   Resolution:
Keywords:               |
-------------------------+--------------------------------------------------
Comment (by stefan):

We need a docstring, something like

{{{
Given a function, use a central difference formula with spacing dx to
compute the nth derivative at x0.

*Parameters*:
func : callable(x,*args)
Function for which the derivative is calculated.
x0 : float or ndarray of floats
Point around which the derivative is calculated.
dx : float
Sample spacing.  To small a step size can lead to
round-off error.
n : int
Calculate the n-th derivative.
order : int
Number of points to take into account.  Must be odd.
}}}

The weights can be defined using dicts, and the order semi-automatically
determined:

{{{
if order < n+1:
d,m = divmod(n,2)
order = d*2 + 1
assert (order % 2 == 1), "Odd number of points only."
# pre-computed for n=1 and 2 and low-order for speed.
if n==1:
weights = {3: array([-1,0,1])/2.0,
5: array([1,-8,0,8,-1])/12.0,
7: array([-1,9,-45,0,45,-9,1])/60.0,
9: array([3,-32,168,-672,0,672,-168,32,-3])/840.0}
elif n==2:
weights = {3: array([1,-2.0,1]),
5: array([-1,16,-30,16,-1])/12.0,
7: array([2,-27,270,-490,270,-27,2])/180.0,
9:
array([-9,128,-1008,8064,-14350,8064,-1008,128,-9])/5040.0}
else:
weights = {}

weights = weights.get(order,central_diff_weights(order,n))
}}}

I'd also replace the ">>" with "divmod", to make it clearer that there is
division by two.

Some tests + examples in the docstring would be really great too.

I think the last for-loop can be vectorised.

--
Ticket URL: <http://scipy.org/scipy/scipy/ticket/564#comment:2>
SciPy <http://www.scipy.org/>
SciPy is open-source software for mathematics, science, and engineering.
```