Reputation: 33
We are trying to switch from Mathematica to python with sympy. Unfortunately sympy is not that mighty. One task for our students was to calculate the resulting oscillation in the form
from the given form
I tried several common simplifying tools from sympy like simplify, trigsimp but nothing worked. Sympy just simplifys every term like
Does anyone know how to solve this task with sympy or other python modul ?
Upvotes: 2
Views: 679
Reputation: 1370
So I couldn't find a way to do it automatically using SymPy. I even tried sympy.physics.optics.waves.TWave
which seemed to be for this very thing. But after a long time of trying, I am convinced there is a bug in that code. The superposition in that code is not even associative.
So instead we solve it ourselves. We first get the expression into the form a*sin(t) + b*cos(t)
. We then solve a simultaneous equation: a = A * cos(c)
and b = A * sin(c)
. Since this this can be precomputed we do so. The final answer will be A*cos(t-c)
.
Here is the code that does this:
from sympy import *
t = symbols('t', real=True)
expr = 2*sin(t+S(3)/10) + 5*cos(t + pi/4) + cos(t - S(31)/10)
d = collect(expr.expand(trig=True), [sin(t), cos(t)], evaluate=False)
a = d[sin(t)]
b = d[cos(t)]
cos_phase = atan(a/b)
amplitude = a / sin(cos_phase)
print(amplitude.evalf() * cos(t - cos_phase.evalf()))
Giving
3.50537475229229*cos(t + 0.468638709416397)
After plotting both graphs, they seem correct.
Note that this code above does not work for different frequencies of t
.
Upvotes: 1