python - 如何简化 SymPy 中的正弦和余弦之和?
问题描述
如何简化a*sin(wt) + b*cos(wt)
为c*sin(wt+theta)
使用 SymPy?例如:
f = sin(t) + 2*cos(t) = 2.236*sin(t + 1.107)
我尝试了以下方法:
from sympy import *
t = symbols('t')
f=sin(t)+2*cos(t)
trigsimp(f) #Returns sin(t)+2*cos(t)
simplify(f) #Returns sin(t)+2*cos(t)
f.rewrite(sin) #Returns sin(t)+2*sin(t+Pi/2)
PS.:我没有直接访问权限a,b and w
。只为f
有什么建议吗?
解决方案
一般的答案可以通过注意你想要
a * sin(t) + b * cos(t) = A * (cos(c)*sin(t) + sin(c)*cos(t))
这导致一个联立方程a = A * cos(c)
和b = A * sin(c)
。
将第二个方程除以第二个,我们可以求解c
。将其解代入第一个方程,您可以求解A
。
我遵循相同的模式,但只是为了得到它的 cos。如果你想从罪的角度得到它,你可以使用罗德里戈的公式。
以下代码应该能够采用 x * sin(t - w) 或 y * cos(t - z) 形式的任何线性组合。可以有多个罪和 cos'。
from sympy import *
t = symbols('t', real=True)
expr = sin(t)+2*cos(t) # unknown
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()))
这使
2.23606797749979*cos(t - 0.463647609000806)
在绘制这两个图表之后,这似乎是一个令人满意的匹配。
你甚至可以有类似的东西
expr = 2*sin(t - 3) + cos(t) - 3*cos(t - 2)
它应该可以正常工作。