Simplification of Trigonometric Addition Formulas with SymPy

57 Views Asked by At

I was checking a trigonometric addition formula

cos(x)*cos(y) - sin(x)*sin(y) = cos(x+y)

using trigsimp() in SymPy.

from sympy import cos, sin, symbols, trigsimp

q = symbols('q')
print('trigsimp')
print(trigsimp(-sin(q)*sin(1*q) + cos(q)*cos(1*q)))
print(trigsimp(-sin(q)*sin(2*q) + cos(q)*cos(2*q)))
print(trigsimp(-sin(q)*sin(3*q) + cos(q)*cos(3*q)))
print(trigsimp(-sin(q)*sin(4*q) + cos(q)*cos(4*q)))
print(trigsimp(-sin(q)*sin(5*q) + cos(q)*cos(5*q)))
print(trigsimp(-sin(q)*sin(6*q) + cos(q)*cos(6*q)))

and the results are

trigsimp
cos(2*q)
cos(3*q)
cos(4*q)
-sin(q)*sin(4*q) + cos(q)*cos(4*q)
cos(6*q)
cos(7*q)

As shown above, the expression -sin(q)*sin(4*q) + cos(q)*cos(4*q)) was not simplified to cos(5*q).

I tried simplify() but the results were same.

Is this a type of pitfalls of the simplification in SymPy, or is there a way to simplify the expression above? I tried this condition with Python 3.8.5 and SymPy 1.11.1.

Thank you in advance for your help,

1

There are 1 best solutions below

4
smichr On

Fu, et al., developed an algorithm which applies transformations in a smart fashion to try to automatically come to a state a human work towards when simplifying a trigonometric expression. simplify and trigsimp use their own order of steps. In this case, fu is better:

from sympy import fu
>>> fu(-sin(q)*sin(4*q) + cos(q)*cos(4*q))
cos(5*q)

Beside the fu algorithm there is a dictionary with the individual "steps" in it that can be applied (or read about). In this case, TR8 and TR10i make the desired change:

>>> from sympy.simplify.fu import FU
>>> [i for i in FU if FU[i](-sin(q)*sin(4*q) + cos(q)*cos(4*q)) == cos(5*q)]
['TR8', 'TR10i']

>>> from sympy.simplify.fu import TR8
>>> [TR8(-sin(q)*sin(i*q) + cos(q)*cos(i*q)) for i in range(1,10)]
[cos(2*q), cos(3*q), cos(4*q), cos(5*q), cos(6*q), cos(7*q), cos(8*q), cos(9*q), cos(10*q)]