I'm writing program in Python and I need to find the derivative of a function (a function expressed as string).
- For example:
x^2+3*x
- Its derivative is:
2*x+3
Are there any scripts available, or is there something helpful you can tell me?
I'm writing program in Python and I need to find the derivative of a function (a function expressed as string).
x^2+3*x
2*x+3
Are there any scripts available, or is there something helpful you can tell me?
Unless any already made library deriving it's quite complex because you need to parse and handle functions and expressions.
Deriving by itself it's an easy task, since it's mechanical and can be done algorithmically but you need a basic structure to store a function.
If you are limited to polynomials (which appears to be the case), there would basically be three steps:
If you need to handle polynomials like a*x^15125 + x^2 + c
, using a dict
for the list of coefficients may make sense, but require a little more attention when doing the iterations through this list.
Symbolic Differentiation is an impressive introduction to the subject-at least for non-specialist like me :) The code is written in C++ btw.
Look up automatic differentiation. There are tools for Python. Also, this.
You may find what you are looking for in the answers already provided. I, however, would like to give a short explanation on how to compute symbolic derivatives.
The business is based on operator overloading and the chain rule of derivatives. For instance, the derivative of v^n
is n*v^(n-1)dv/dx
, right? So, if you have v=3*x
and n=3
, what would the derivative be? The answer: if f(x)=(3*x)^3
, then the derivative is:
f'(x)=3*(3*x)^2*(d/dx(3*x))=3*(3*x)^2*(3)=3^4*x^2
The chain rule allows you to "chain" the operation: each individual derivative is simple, and you just "chain" the complexity. Another example, the derivative of u*v
is v*du/dx+u*dv/dx
, right? If you get a complicated function, you just chain it, say:
d/dx(x^3*sin(x))
u=x^3; v=sin(x)
du/dx=3*x^2; dv/dx=cos(x)
d/dx=v*du+u*dv
As you can see, differentiation is only a chain of simple operations.
Now, operator overloading.
If you can write a parser (try Pyparsing) then you can request it to evaluate both the function and derivative! I've done this (using Flex/Bison) just for fun, and it is quite powerful. For you to get the idea, the derivative is computed recursively by overloading the corresponding operator, and recursively applying the chain rule, so the evaluation of "*"
would correspond to u*v for function value and u*der(v)+v*der(u)
for derivative value (try it in C++, it is also fun).
So there you go, I know you don't mean to write your own parser - by all means use existing code (visit www.autodiff.org for automatic differentiation of Fortran and C/C++ code). But it is always interesting to know how this stuff works.
Cheers,
Juan
wow,thanks a lot you all.
sympy works i dont believe thanks. :)
thanks again. Solved. :)