I am trying to solve a differential equation with sympy module in python. This is what I did
from sympy import *
t = sympy.Symbol('t')
k = sympy.Symbol('k')
m = sympy.Symbol('m')
x = sympy.Function('x')(t)
GDE = Eq(m*x.diff(t, 2) + k*x, 0)
solution = dsolve(GDE, x)
display(solution)
Now, I am trying to get a solution in polar form with both sin, cos and complex term (i) like this picture. In this picture, w_n is sqrt(k/m)
I tried
solution.rewrite(sin)
but it returns an expression with hyperbolic functions .rewrite(cos) also returns an expression with hyperbolic functions.
I also tried
solution.rewrite(sin, cos)
but it gives the initial answer.
Is there any way to convert this exponential form of complex form to polar form without hyperbolic functions?
Thank you
You should declare your symbols as real or positive etc. Otherwise by default SymPy assumes something like a complex number:
In [7]: import sympy
In [8]: from sympy import *
...:
...:
...: t = sympy.Symbol('t', real=True)
...: k = sympy.Symbol('k', positive=True)
...: m = sympy.Symbol('m', positive=True)
...: x = sympy.Function('x', real=True)(t)
...:
...: GDE = Eq(m*x.diff(t, 2) + k*x, 0)
Then various simplifications will happen automatically:
In [9]: sqrt(-k/m)
Out[9]:
ⅈ⋅√k
────
√m
In [10]: exp(t * sqrt(-k/m))
Out[10]:
ⅈ⋅√k⋅t
──────
√m
ℯ
In [11]: exp(t * sqrt(-k/m)).rewrite(cos)
Out[11]:
⎛√k⋅t⎞ ⎛√k⋅t⎞
ⅈ⋅sin⎜────⎟ + cos⎜────⎟
⎝ √m ⎠ ⎝ √m ⎠
In fact with the assumptions set dsolve
will give the sin
, cos
form automatically:
In [12]: dsolve(GDE)
Out[12]:
⎛√k⋅t⎞ ⎛√k⋅t⎞
x(t) = C₁⋅sin⎜────⎟ + C₂⋅cos⎜────⎟
⎝ √m ⎠ ⎝ √m ⎠
Without these assumptions set it is still possible to manipulate the expression into the sin/cos
form but some force=True
is needed to override the assumptions checking:
In [25]: s = solution.rhs; s
Out[25]:
_____ _____
╱ -k ╱ -k
-t⋅ ╱ ─── t⋅ ╱ ───
╲╱ m ╲╱ m
C₁⋅ℯ + C₂⋅ℯ
In [26]: s = expand(s, force=True); s
Out[26]:
___ ___
╱ 1 ╱ 1
-ⅈ⋅√k⋅t⋅ ╱ ─ ⅈ⋅√k⋅t⋅ ╱ ─
╲╱ m ╲╱ m
C₁⋅ℯ + C₂⋅ℯ
In [27]: s = s.rewrite(sin); s
Out[27]:
⎛ ⎛ ___⎞ ⎛ ___⎞⎞ ⎛ ⎛ ___⎞ ⎛ ___⎞⎞
⎜ ⎜ ╱ 1 ⎟ ⎜ ╱ 1 ⎟⎟ ⎜ ⎜ ╱ 1 ⎟ ⎜ ╱ 1 ⎟⎟
C₁⋅⎜- ⅈ⋅sin⎜√k⋅t⋅ ╱ ─ ⎟ + cos⎜√k⋅t⋅ ╱ ─ ⎟⎟ + C₂⋅⎜ⅈ⋅sin⎜√k⋅t⋅ ╱ ─ ⎟ + cos⎜√k⋅t⋅ ╱ ─ ⎟⎟
⎝ ⎝ ╲╱ m ⎠ ⎝ ╲╱ m ⎠⎠ ⎝ ⎝ ╲╱ m ⎠ ⎝ ╲╱ m ⎠⎠
In [28]: s = expand(s).collect(s.atoms(sin, cos)); s
Out[28]:
⎛ ___⎞ ⎛ ___⎞
⎜ ╱ 1 ⎟ ⎜ ╱ 1 ⎟
(C₁ + C₂)⋅cos⎜√k⋅t⋅ ╱ ─ ⎟ + (-ⅈ⋅C₁ + ⅈ⋅C₂)⋅sin⎜√k⋅t⋅ ╱ ─ ⎟
⎝ ╲╱ m ⎠ ⎝ ╲╱ m ⎠
In [29]: s = powsimp(s, force=True); s
Out[29]:
⎛ ___⎞ ⎛ ___⎞
⎜ ╱ 1 ⎟ ⎜ ╱ 1 ⎟
(C₁ + C₂)⋅cos⎜√k⋅t⋅ ╱ ─ ⎟ + (-ⅈ⋅C₁ + ⅈ⋅C₂)⋅sin⎜√k⋅t⋅ ╱ ─ ⎟
⎝ ╲╱ m ⎠ ⎝ ╲╱ m ⎠
In [30]: s = powsimp(s, force=True, deep=True); s
Out[30]:
⎛ ___⎞ ⎛ ___⎞
⎜ ╱ k ⎟ ⎜ ╱ k ⎟
(C₁ + C₂)⋅cos⎜t⋅ ╱ ─ ⎟ + (-ⅈ⋅C₁ + ⅈ⋅C₂)⋅sin⎜t⋅ ╱ ─ ⎟
⎝ ╲╱ m ⎠ ⎝ ╲╱ m ⎠