13

I'm interested in computing partial derivatives in Python. I've seen functions which compute derivatives for single variable functions, but not others.

It would be great to find something that did the following

    f(x,y,z) = 4xy + xsin(z)+ x^3 + z^8y
    part_deriv(function = f, variable = x)
    output = 4y + sin(z) +3x^2

Has anyone seen anything like this?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
cnrk
  • 185
  • 1
  • 2
  • 10

2 Answers2

28

use sympy

>>> from sympy import symbols, diff
>>> x, y, z = symbols('x y z', real=True)
>>> f = 4*x*y + x*sin(z) + x**3 + z**8*y
>>> diff(f, x)
4*y + sin(z) + 3*x**2
wtayyeb
  • 1,879
  • 2
  • 18
  • 38
  • Thank you for your response! I don't understand why the symbols part is important, but from fooling around with the code I see that it definitely is. I'm all set :) – cnrk Jun 12 '15 at 13:54
  • 3
    @crnk because it is computer not math on the paper! so simple variable will resolve to its value when manipulating. eg. if `x=1` when you use x the compiler will put 1 instead of x. so we define something (named symbol instance) and put it in x. and when `x` used, the symbol will put in action and the formula remain non-calculated. so it could to be send to functions like `diff` to work on symbols. – wtayyeb Jun 12 '15 at 17:08
  • Is there a way to use the symbols y, z and x as variables again afterwards? so if i assign ```x, y, z = 5, 4, 3```, I'd like to get a result as float... – prog2de Apr 22 '20 at 11:58
  • @prog2de: You can [substitute actual values](https://docs.sympy.org/latest/tutorials/intro-tutorial/basic_operations.html#substitution) to symbols for the expression returned by `diff`, e.g. `diff(f, x).subs((x,1),(y,2),(z,3))` – mins Oct 31 '22 at 09:06
4

Use sympy


From their Docs:

>>> diff(sin(x)*exp(x), x)
 x           x
ℯ ⋅sin(x) + ℯ ⋅cos(x)

and for your example:

>>> diff(4*x*y + x*sin(z)+ x**3 + z**8*y,x)
3x**2+4*y+sin(z)
Nitish
  • 6,358
  • 1
  • 15
  • 15