How to solve the multi object problem?
import sympy as sym from sympy import lambdify x = sym.Symbol('x') n = sym.Symbol('n') f = sym.sin(n*x) derivative_f = f.diff(x) derivative_f = lambdify(x, derivative_f) x = float(input('x:')) print(derivative_f(x)) print(derivative_f)
If I input 2, the expected result should be 2*cos(2*x)
.
Advertisement
Answer
Your code contains a few misconceptions. One problem is an important general programming rule: try to use different variable names for variables with different meanings. So, x
shouldn’t be assigned a float, as it was a symbolic variable before. And derivative_f
being a symbolic expression, shouldn’t be assigned the result of lambdify
.
Note that sympy
‘s symbolic world doesn’t mix well with the numeric world of non-sympy functions. lambdify
forms a bridge between these worlds, from completely symbolic to completely numeric. E.g. the function created with lambdify
doesn’t have access to the symbolic n
anymore.
The code lambdify(x, derivative_f)
contains an error. derivative_f
is a symbolic expression containing two symbolic variables (x
and n
), so it needs to be called as derivative_f_x_n = lambdify((x, n), derivative_f)
(also giving the result a different name). Afterwards, you can use numeric expressions as derivative_f_x_n(7, 8)
, but you can’t use symbolic parameters anymore.
For what you seem to be trying to do, lambdify
isn’t adequate. To get the derivative with x
substituted, you call .subs(x, new_value)
directly on the symbolic version of derivative_f
:
import sympy as sym from sympy import lambdify x = sym.Symbol('x') n = sym.Symbol('n') f = sym.sin(n * x) derivative_f_x = f.diff(x) x_float = 2.0 print(derivative_f_x.subs(x, x_float))
Output: n*cos(2.0*n)
Also note that sympy strongly prefers to work with exact symbolic expressions, and using floats inevitably brings in approximations. Whenever possible, integers, sympy fractions (sym.S(1)/2
) or symbolic expressions (sym.sqrt(5)
) are recommended.
You call also use the derivative with respect to x
and then substitute n
:
print(f.diff(x).subs(n, 2))
Output: 2*cos(2*x)
To use that function later on in numeric calculations, after substitution you only have one symbolic variable left(x
):
g = lambdify(x, f.diff(x).subs(n, 2))
You can type help(g)
to see its generated source code:
Source code: def _lambdifygenerated(x): return (2*cos(2*x))
Then you can use g
e.g. to create matplotlib plot. After lambdify
nothing is symbolic anymore.
import matplotlib.pyplot as plt import numpy as np xs = np.linspace(0, 10) plt.plot(xs, g(xs))