Trigonometry is a pretty deal in most of Mathematica, so you might be wondering how you can include trigonometric functions and identities within your mathematical expressions. Let’s take a look at how to include Trigonometric Functions in our Python Code using Sympy!
Using Trigonometric Functions
In order to use Trigonometric functions in SymPy, we need to first make sure they are imported.
If you have import sympy with the statement import sympy
, then you will have to access them using like: sympy.cos
or sympy.sin
. So either use from sympy import *
, or from sympy import cos, sin
. We will be using the latter approach.
Here’s a simple trigonometric function, sin(x)
, that we will use. Let’s plug in a few values, just to verify the output. These input values of x are in radians.
from sympy import symbols, cos, sin
x, y = symbols("x y")
expr = sin(x)
print(expr.subs(x, 0))
print(expr.subs(x, 3))
0
sin(3)
Sympy will either output a numerical value, or a SymPy object representation. (Depending on whether it can accurately give a numerical value).
You can however, force it to give you a numerical representation using the Function “N()
“.
from sympy import symbols, cos, sin, N
x, y = symbols("x y")
expr = sin(x)
print(expr.subs(x, 0))
print(N(expr.subs(x, 3)))
0
0.141120008059867
Taking Input in Radians
But what if you want to take the input in degrees, and not radians? Often we just have the degree that we want to us as “x”, but we don’t know it’s radian equivalent. Luckily, we can use the radians function mpmath
. (This library should have already been installed when you downloaded sympy, so don’t worry).
from mpmath import radians
expr = sin(x)
print(expr.subs(x, radians(360)))
print(expr.subs(x, radians(90)))
-2.44929359829471e-16
1.00000000000000
Here we have something interesting in the output. Instead of 0 in the first output, we have a very small value instead. This is because of floating point rounding error, due to the value of pi
not being correctly approximated. Not really something you can avoid, but can filter out.
Simplifying Trigonometric Identities
Another cool thing we can do SymPy, is to simplify trigonometric identities. (No need to memorize any of them anymore!) SymPy will automatically attempt to simplify any expression you pass into the trigsimp()
function.
Let’s take a look at 3 popular trigonometric identities, and see how SymPy is able to simplify then.
x, y = symbols("x y")
print(trigsimp(sin(x)**2 + cos(x)**2))
print(trigsimp(sin(x)**4 - 2*cos(x)**2*sin(x)**2 + cos(x)**4))
print(trigsimp(sin(x)*tan(x)/sec(x)))
1
cos(4*x)/2 + 1/2
sin(x)**2
Interested in learning more about sympy? Check out our extensive compilation of SymPy Tutorials!
This marks the end of the Trigonometric Functions in SymPy Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.