3

I want to plot the second derivative of the Hankel function using Simpy. In Mathematica it is as easy as:

D[HankelH2[1,z],z]

This can be done analytically by using the property,

The first derivative of the Hankel function of the second kind and first order is equal to the difference between two Hankel functions of the second kind of order zero and two, respectively, all these divided by two.

But I want to learn how to derivate it directly using Sympy. So far I've tried this:

from scipy.special import hankel2
import sympy as sp
x = sp.Symbol('x')
dh2 = sp.diff(lambda x: hankel2(1,x),x)

The error message seems illegible to me:

SympifyError Traceback (most recent call last) in () 1 import sympy as sp 2 x = sp.Symbol('x') ----> 3 dh2 = sp.diff(lambda x: hankel2(1,x),x)

/usr/lib/python2.7/dist-packages/sympy/core/function.pyc in diff(f, *symbols, **kwargs) 1639 """ 1640 kwargs.setdefault('evaluate', True) -> 1641 return Derivative(f, *symbols, **kwargs) 1642 1643

/usr/lib/python2.7/dist-packages/sympy/core/function.pyc in new(cls, expr, *variables, **assumptions) 985 def new(cls, expr, *variables, **assumptions): 986 --> 987 expr = sympify(expr) 988 989 # There are no variables, we differentiate wrt all of the free symbols

/usr/lib/python2.7/dist-packages/sympy/core/sympify.pyc in sympify(a, locals, convert_xor, strict, rational, evaluate) 313 expr = parse_expr(a, local_dict=locals, transformations=transformations, evaluate=evaluate) 314 except (TokenError, SyntaxError) as exc: --> 315 raise SympifyError('could not parse %r' % a, exc) 316 317 return expr

SympifyError: Sympify of expression 'could not parse u' at 0x7fdf3eca9e60>'' failed, because of exception being raised: SyntaxError: invalid syntax (, line 1)

Any clue where is my mistake?

Thanks in advance.

gtlambert
  • 11,711
  • 2
  • 30
  • 48
Felipe BM
  • 43
  • 3

1 Answers1

3

You can't use SciPy functions with SymPy. SciPy functions are numeric, whereas SymPy only works with symbolic functions (i.e., those inside of SymPy itself). Wrapping it in a lambda doesn't change this.

What you need to do is import hankel2 from SymPy, and use that.

>>> from sympy import hankel2, symbols, diff
>>> x = symbols('x')
>>> diff(hankel2(1, x), x)
hankel2(0, x)/2 - hankel2(2, x)/2

If you want to then plot this, you can use the sympy.plot function. Or, you can convert it to a numeric function using scipy with

l = lambdify(x, diff(hankel2(1, x), x), {'hankel2': scipy.special.hankel2})

and use that with a plotting library like maptlotlib (it looks like hankel2 is a complex function, which I don't think SymPy's plot handles very well right now, so you may prefer this option).

asmeurer
  • 86,894
  • 26
  • 169
  • 240