1

I am using Sympy to calculate the derivative of a complicated potential. I have defined x, y, D0, e, C, k, d, b as Sympy Symbols. Then I go on to do the following definitions:

import sympy as sm
x, y, D0, e, C, k, d, b = sm.symbols("x, y, D0, e, C, k, d, b")
phi = sm.atan2(y,x)
D = D0 + e*D0*sm.sin(k*phi)
rho = sm.sqrt(x**2 + y**2)

U = (2**b)/((2*D-d)**b)*(D - rho)**b

The symbol "U" stands for the 2D potential.

Now when I differentiate this vs. x using:

sm.simplify(U.diff(x))

I get an extremely long answer: extremely long naswer

As you can see, in the answer there is explicitly the full expression for e.g. D : D0 + e*D0*sin(k*phi) . Also, instead of sin(phi) I get sin(atan2(x,y) and the same happens for all of my defined expressions.

Is there a way for the result to automatically show my definitions instead of the long versions, without having the need to use the subs method for every single user-defined variable?

E.g. instead of D0 + e*D0*sin(k*phi) Sympy automatically uses the symbol D?

user
  • 5,370
  • 8
  • 47
  • 75
George Datseris
  • 411
  • 4
  • 14

1 Answers1

1

When you write phi = sm.atan2(y,x), this assigns a Python variable to the result of atan2(y, x). If you want phi to be a symbol, you have to define it that way

phi = symbols('phi')

and then substitute phi in as atan2(y, x) later.

U.subs(phi, atan2(y, x))

This is worth reading regarding this.

asmeurer
  • 86,894
  • 26
  • 169
  • 240
  • Thank you for your answer, however it does not help me. As I stated in my question I am (was) looking for a way to do this without having to use the `subs` method for each variable. Furthermore, I still need the 'python variable' phi to actually write the potential, otherwise it gets way to complicated. So if I were to follow your answer, I would have to add 6 more commands to the existing code to redefine the references and do the substitutions. I have also read 'this" before I even started to use sympy, as part of my study. It does not give any information for what I want to do. – George Datseris Apr 22 '16 at 08:18
  • What I want to do is to have PRE-defined expressions that are automatically included in the results of the sympy calculations without the need of `subs`. I use many different potentials. – George Datseris Apr 22 '16 at 08:19
  • 2
    @GeorgeDatseris SymPy requires you to be explicit about when you want to replace symbols with expressions in your calculations. I recommend building up a list of `(symbol, expr)` pairs for your calculation and using `subs` to replace them to the full expression at whatever point in your calculation you wish to replace them. You can do the whole thing using a single subs call if you pass a list of replacements to `subs`. – asmeurer Apr 22 '16 at 20:17
  • Yes, thank you. This seems the most efficient way. As I understand now, there is not any option that does not include an extra use of subs. So thank you for both of your answers. – George Datseris May 19 '16 at 12:00