2012-07-13 10 views
6

Ho una domanda sulla funzione derivata di Scipy. L'ho usato la scorsa notte e ho ottenuto alcune risposte strane. Ho provato di nuovo stamattina con alcune semplici funzioni e ho ottenuto alcune risposte giuste e alcune sbagliate. Qui sono stati i miei test:Scipy Derivative

In [1]: def poly1(x): 
...:  return x**2 

In [3]: derivative(poly1, 0) 
Out[3]: 0.0 

In [4]: def poly2(x): 
...: return (x-3)**2 

In [6]: derivative(poly2, 3) 
Out[6]: 0.0 

In [8]: def sin1(x): 
...:  return sin(x) 

In [14]: derivative(sin1, pi/2) 
Out[14]: 5.5511151231257827e-17 

In [15]: def poly3(x): 
....:  return 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2 

In [19]: derivative(poly3, -2) 
Out[19]: -39.0 

In [20]: derivative(poly3, 2) 
Out[20]: 121.0 

In [22]: derivative(poly3, 0) 
Out[22]: 17.0 

ho controllato i valori di Poly3 a mano e -2 = 17, 2 = 95, 0 = 15. Così sto utilizzando la funzione sbagliata, o c'è qualcosa di sbagliato con la funzione . Grazie

Usando: Python 2.7.3, IPython 0.12.1, Numpy 1.6.1, SciPy 0.9.0, Linux Mint 13

risposta

15

quanto la documentazione per derivative dice:

derivative(func, x0, dx=1.0, n=1, args=(), order=3) 
    Find the n-th derivative of a function at point x0. 

    Given a function, use a central difference formula with spacing `dx` to 
    compute the n-th derivative at `x0`. 

si didn 't specificare dx, quindi ha utilizzato il valore predefinito di 1, che è troppo grande qui. Ad esempio:

In [1]: from scipy.misc import derivative 

In [2]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=1) 
Out[2]: -39.0 

In [3]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=0.5) 
Out[3]: -22.5 

In [4]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=0.1) 
Out[4]: -17.220000000000084 

In [5]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=0.01) 
Out[5]: -17.0022000000003 

In [6]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=1e-5) 
Out[6]: -17.000000001843318 

In alternativa, si potrebbe aumentare l'ordine:

In [7]: derivative(lambda x: 3*x**4 + 2*x**3 - 10*x**2 + 15*x - 2, -2, dx=1, order=5) 
Out[7]: -17.0 

Prendendo derivate numeriche è sempre un po 'fastidioso.

+0

Ah, grazie, ho letto la documentazione e non l'ho capito molto bene. Sarebbe bello se fornissero un esempio come questo per mostrare come funzionano le altre opzioni. Grazie ancora – user1523697