Plotting Expressions and Solving Equations Numerically
In this example, we demonstrate how to plot functions in Python and how to use these plots to help obtain numerical approximations of solutions to equations which are difficult or impossible to solve symbolically in Python. If you watched the video on symbolic solutions to equations, we attempted to solve the equation 50*tan(theta) -13.61/cos(theta)^2=0 to determine the angle for a Braden Mann punt. You may have also noticed that the process was very complicated due to complex residues. To obtain a numerical solution, we plot the expression on the left. First, in a Jupyter notebook, we run the command matplotlib notebook, which tells Python to create a new graph within the notebook. Next, we define theta as a symbolic variable, then define our left-hand side to be LHS, and finally using the plot command. For the context of this problem, it only makes practical sense for theta to be between 0 and pi/2 exclusive. Since pi/2 is about 1.57, we will use the domain 0 to 1.5. Notice how we enter the domain: (x,0,1.5). The parenthetical expression is called a tuple in Python, and we always use that for the domain of a symbolic plot. To get a better picture of when this graph is equal to 0, we can modify the y-range using the ylim option in the plot command. Letâ€™s set the range from -20 to 20. When we do, we see the graph is 0 (crosses the x-axis) at about 0.3 and about 1.3. These will constitute starting guesses for our numerical solution, which we find using the nsolve command. The syntax is nsolve(expression, initial guess). Of course, these solutions are in radians, so we convert to degrees by multiplying by 180/pi, noting as when we solved symbolically that we have to convert pi to a decimal using the evalf command.