Sympy function derivatives using custom method

694 views Asked by At

I am working on a program that needs to take user input (usually equations) in the form of strings. A lot of stuff is then done to these equations, such as calculating partial derivatives, numerical integration etc.

What I want to be able to do is, have the user define a string such as:

xdot = '0.5*rho*V**2*CL(aoa)*Aref'

aoa, rho, V, Aref are all defined as symbolic variables. These get converted into sympy expressions using sympify(). I later use these symbolic expressions (and stuff I calculate using them) to create python functions in memory by placing these expressions into a template and running exec().

I know I can make the template such that these custom functions are defined locally at the point where these expressions are written out so that they get called when these expressions get evaluated at runtime. The problem is, I also take partial derivatives of these expressions, usually resulting in something that has:

Derivative(CL(aoa), aoa)

as part of it. I want to be able to substitute/evaluate these using numerical derivatives at runtime.

Should I traverse the expression and substitute each "Derivative" element with some finite difference expression like: (CL(aoa + h) - CL(aoa))/h # Or something else

Or is it possible to subclass Function or Derivative and make it so it uses a numerical derivative method of my choice without having to do this for manually for each expression? I could not find too many references on this.

What would be the 'pythonic' way of doing this?

0

There are 0 answers