justin
justin

Reputation: 181

Adding an angle to a sum of trig functions

I have an expression which is the sum of some trig functions:

import sympy as sy
from sympy import cos,sin,pi

theta = sy.symbols('theta')

expr = 5*cos(theta) + sin(theta*2)+3*cos(3*theta)

I'd like to add a "phase shift" by pi/4 to each trig function:

sin(2*theta + pi/4) + 5*cos(theta + pi/4) + 3*cos(3*theta + pi/4)

How can this be achieved? Is there a way to walk the expression tree and do an insertion of pi/4?

Upvotes: 0

Views: 57

Answers (1)

Oscar Benjamin
Oscar Benjamin

Reputation: 14480

There are many ways to do this. Here is one that uses pattern matching:

In [5]: expr
Out[5]: sin(2⋅θ) + 5⋅cos(θ) + 3⋅cos(3⋅θ)

In [6]: w = Wild('w')

In [7]: expr.replace(sin(w), sin(w+pi/4))
Out[7]: 
   ⎛      π⎞                        
sin⎜2⋅θ + ─⎟ + 5⋅cos(θ) + 3⋅cos(3⋅θ)
   ⎝      4⎠                        

In [8]: expr.replace(sin(w), sin(w+pi/4)).replace(cos(w), cos(w + pi/4))
Out[8]: 
   ⎛      π⎞        ⎛    π⎞        ⎛      π⎞
sin⎜2⋅θ + ─⎟ + 5⋅cos⎜θ + ─⎟ + 3⋅cos⎜3⋅θ + ─⎟
   ⎝      4⎠        ⎝    4⎠        ⎝      4⎠

Upvotes: 1

Related Questions