Solving Equations Symbolically
In this example, we demonstrate how to solve equations symbolically in Python. Suppose former A&M punter Braden Mann wants to punt a ball 50 meters, and the ball leaves his foot with initial velocity 30 meters per second. To determine the angle, in degrees, at which the ball needs to be kicked, it can be shown that the answer is found by solving the equation 50*tan(theta) -13.61/cos(theta)^2=0. To solve this in Python, we define the symbolic variable theta using the symbols command, then define an expression, which we will call LHS, to be the left-hand side of the equation. The solve command follows the traditional syntax: solve(LHS,theta). Notice we get a list of answers, all in radians. It appears that two of the answers are complex, but looking carefully, we see that the imaginary part is almost nothing. When solving equations symbolically with floating point values, sometimes Python will create an infintessimal imaginary part due to round-off, so we can ignore it in this case. Knowing theta has to be between 0 and pi/2, we see that only the third and fourth answers in the list make sense, so we can assign a name like thsol to this list and use subscripts in square brackets to refer to these specific values. HOWEVER, it is important to note that when Python counts the elements in a list, it starts counting at ZERO. So the third and fourth answers in the list are thsol[2] and thsol[3]! Since we want only the real part of the solutions, we can use the re command. Next, we want to convert to degrees by multiplying by 180/pi. Finally, we notice when we do this that Python leaves the pi expression in the denominator. We can convert to a decimal by using the evalf command, either just on pi, or on the entire expression in parentheses. So our final answers are either about 16.5 degrees or 73.5 degrees.