1

using symbolic calculation in Python I have

import sympy
from cmath import *
from mpmath import arg, cplot

z = sympy.symbols('z')

fhandle='z**2'
g = lambda w: sympy.sympify(fhandle).evalf(subs={z: w})
g(1+2j)

# Returns: -3.0 + 4.0*I
# hence the next command fails, because I is expected to be 1j

cplot(g, [-3,3], [-3,3])

Crawling the web I only found this which will fix the matter for the print command, but will not work with cplot.

Any suggestions?

3
  • You are abusing sympify. When you can (which is almost always) write actual code, not strings to be passed to sympify.
    – Krastanov
    May 23, 2013 at 15:45
  • @Krastanov This is the minimum working example. fhandle will be passed as a string from the web interface. Still abusive?
    – arney
    May 23, 2013 at 16:00
  • 1
    Oh, not in this case, sorry. But there is now another bigger issue: sympify may parse code through eval, which means that you are exposing your app to injections. It is not an issue if you can trust the users, but it is good to know anyway.
    – Krastanov
    May 23, 2013 at 16:18

1 Answer 1

6

One option is to wrap the result by calling complex:

>>> def g(w):
...     return complex(sympy.sympify(fhandle).evalf(subs={z: w}))
... 
>>> g(1+2j)
(-3+4j)

After which mpmath.cplot(g, [-3, 3], [-3, 3]) produces

cplot example

Note that I've used a named function here. There's not much point to using a lambda if you're going to immediately give it a name anyhow.

1
  • Note: this works because I has a method called __complex__(..). Oct 28, 2016 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.