Reputation: 71
I use Jupyter Notebook. How come this does not work when I want to evaluate the partial derivative at the point P?
from sympy import *
P = (-3,-2)
def f(x,y):
return x**3+3*x**2-9*x+y**3-12*y
def f_x(x,y):
return diff(f(x,y), x)
When I type f(P[0],P[1]), I get the answer 43.
When I type f_x(x,y), I get the derivative of f wrt. x
Then, when I type f_x(P[0],P[1]), I get this error:
ValueError Traceback (most recent call last) <ipython-input-2-2afed429d2a2> in <module>
7 return diff(f(x,y), x)
8
----> 9 f_x(P[0],P[1])
<ipython-input-2-2afed429d2a2> in f_x(x, y)
5 return x**3+3*x**2-9*x+y**3-12*y
6 def f_x(x,y):
----> 7 return diff(f(x,y), x)
8
9 f_x(P[0],P[1])
~\anaconda3\lib\site-packages\sympy\core\function.py in diff(f,
*symbols, **kwargs) 2503 return f.diff(*symbols, **kwargs) 2504 kwargs.setdefault('evaluate', True)
-> 2505 return _derivative_dispatch(f, *symbols, **kwargs) 2506 2507
~\anaconda3\lib\site-packages\sympy\core\function.py in
_derivative_dispatch(expr, *variables, **kwargs) 1945 from sympy.tensor.array.array_derivatives import ArrayDerivative 1946 return ArrayDerivative(expr, *variables, **kwargs)
-> 1947 return Derivative(expr, *variables, **kwargs) 1948 1949
~\anaconda3\lib\site-packages\sympy\core\function.py in __new__(cls, expr, *variables, **kwargs) 1312 if isinstance(v, Integer): 1313 if i == 0:
-> 1314 raise ValueError("First variable cannot be a number: %i" % v) 1315 count = v 1316 prev, prevcount = variable_count[-1]
ValueError: First variable cannot be a number: -3
Upvotes: 1
Views: 406
Reputation: 80509
What you are doing:
f_x(P[0], P[1])
becomes
f_x(-3, -2)
becomes
diff(f(-3, -2), -3)
becomes
diff(43, -3)
which gives an error: you can't calculate the derivative of the constant function 43
towards a number (-3
).
In sympy, functions are usually just written as expressions containing symbolic variables (symbols
). Derivatives are calculated directly on the expression. Note that diff(f, x)
can also be written as f.diff(x)
, which might be easier to read.
from sympy import symbols
x, y = symbols('x y')
P = (-3, -2)
# let f be a function of x and y:
f = x**3 + 3*x**2 - 9*x + y**3 - 12*y
# calculate the derivative of f towards x
f_x = f.diff(x) # so, f_x = 3*x**2 + 6*x - 9
# now, fill in the values into the derivative:
f_x.subs({x: P[0], y: P[1]}) # 0
Upvotes: 2