How it works...

In [6]: p = np.poly1d([1,0,0,0,0,0]); 
...: print (p)
5
1 x
In [7]: np.polyder(p,1)(1.0)
In [7]: p.deriv()(1.0)
Out[7]: 5.0 Out[7]: 5.0
In [8]: np.polyder(p,2)(1.0)
In [8]: p.deriv(2)(1.0)
Out[8]: 20.0
Out[8]: 20.0

Symbolic differentiation is another way to achieve exact results:

In [9]: from sympy import diff, symbols
In [10]: x = symbols('x', real=True)
In [11]: diff(x**5, x)
In [12]: diff(x**5, x, x)
Out[11]: 5*x**4
Out[12]: 20*x**3
In [13]: diff(x**5, x).subs(x, 1.0)
Out[13]: 5.00000000000000
In [14]: diff(x**5, x, x).subs(x, 1.0)
Out[14]: 20.0000000000000

Note the slight improvement (both in notation and simplicity of coding) when we differentiate more involved functions than simple polynomials. For example, for g(x) = e-xsinx at x=1:

In [15]: def g(x): return np.exp(-x) * np.sin(x)
In [16]: derivative(g, 1.0, dx=1e-6, order=101)
Out[16]: -0.11079376536871781
In [17]: from sympy import sin as Sin, exp as Exp
In [18]: diff(Exp(-x) * Sin(x), x).subs(x, 1.0)
Out[18]: -0.110793765306699

A great advantage of symbolic differentiation over its numerical or automatic counterparts is the possibility to compute partial derivatives with extreme ease. Let's illustrate this point by calculating a fourth partial derivative of the multivariate function h(x,y,z) = exyz at x=1y=1, and z=2:

In [19]: y, z = symbols('y z', real=True)
In [20]: diff(Exp(x * y * z), z, z, y, x).subs({x:1.0, y:1.0, z:2.0})
Out[20]: 133.003009780752
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset