First of drop all the the unnecessary imports and stick to what you really need. Symbolic math is what sympy
was made for so check out the documentation for that.
In sympy you have to define symbols
first
import sympy
x = symbols('x')
Now you would use the symbol x
to construct an expression using builtin operators and functions in the sympy
module. Be aware that **
is exponentiation and ^
is logical xor.
f = x ** 2 * sympy.exp(-x)
dfdx = sympy.diff(f, x)
d2fdx2 = sympy.diff(f, x, x)
g = sympy.exp(x) / sympy.factorial(2) * d2fdx2
When you write g
in the interactive interpreter it will write the expression the way you want it. Can't show that here but atleast I can do this:
>>> print(g)
x**2/2 - 2*x + 1
You cannot do what you want with the math
, sympy.mpmath
and numpy
modules as they exist for numerical evalutions - they want numbers and give you number.
If you later want to evaluate your expression for a given value of x
you could do
val_at_point = g.evalf(subs={x: 1.5})
where subs
is a dictionary.
Or you could turn g
into a python lambda function:
fun_g = sympy.lambdify(x, g)
val_at_point = fun_g(1.5)
If you're doing this for a math class you probably want to be working in the interpreter anyway in which case you can start by writing
>>> from sympy import *
so that you can skip all the sympy.
stuff in the above code samples. I left them there just to show where symbols come from.