Ecir Hana - 1 year ago 71

Python Question

I have an expression which has both sines and cosines and would like to write it using only sines (or cosines), possibly using the power-reduction formula.

I tried to use SymPy but I cannot make it to "rewrite" to the desired output:

`angle = symbols('angle')`

print (sin(angle)**2).rewrite(sin, cos) # (1 - cos(2*angle))/2

print ((1 - cos(2*angle))/2).rewrite(cos, sin) # sin(angle)**2

Is there any way to tell Sympy to rewrite such expression using only sines (or cosines)?

Answer Source

The `sympy.simplify.fu`

module defines a number of transformations based on trig identities:

```
TR0 - simplify expression
TR1 - sec-csc to cos-sin
TR2 - tan-cot to sin-cos ratio
TR2i - sin-cos ratio to tan
TR3 - angle canonicalization
TR4 - functions at special angles
TR5 - powers of sin to powers of cos
TR6 - powers of cos to powers of sin
TR7 - reduce cos power (increase angle)
TR8 - expand products of sin-cos to sums
TR9 - contract sums of sin-cos to products
TR10 - separate sin-cos arguments
TR10i - collect sin-cos arguments
TR11 - reduce double angles
TR12 - separate tan arguments
TR12i - collect tan arguments
TR13 - expand product of tan-cot
TRmorrie - prod(cos(x*2**i), (i, 0, k - 1)) -> sin(2**k*x)/(2**k*sin(x))
TR14 - factored powers of sin or cos to cos or sin power
TR15 - negative powers of sin to cot power
TR16 - negative powers of cos to tan power
TR22 - tan-cot powers to negative powers of sec-csc functions
TR111 - negative sin-cos-tan powers to csc-sec-cot
```

I learned of these functions from this thread and this post by asmeurer.

```
import sys
import sympy as sy
from sympy import sin, cos
import sympy.simplify.fu
# we can't access the sympy.simplify.fu the normal way because sympy.simplify is
# a function as well as a package.
FU = sys.modules['sympy.simplify.fu']
angle = sy.symbols('angle')
expr = sin(angle)**2
print(FU.TR8(expr))
# -cos(2*angle)/2 + 1/2
print(FU.TR5(expr))
# -cos(angle)**2 + 1
```