Plotting Equaton Roots -

Python Numerical Methods


Roots of equations are commonly needed as solutions to the equation. A root is a value for which a given function equals zero. Unfortunately when applying numerical methods, we require a best guess as to what the roots are. We can take out some of the guesswork by plotting the functions in the range we are interested in. We will use as an example examining the roots for the equation f(x) = sin 10x + cos 3x . We will progressively enlarge the plot of the equation twice, as shown below. The final progressive enlargement shows two roots where we might have expected one.

Roots for the equation f(x) = sin 10x + cos 3x

In this first plot it appears that there is a root at x = 4.25.

Root Plot Program

First make sure the numpy and matplotlib modules are installed. Use linspace to define x values as follows: linspace(Start of interval, End of interval, Number of items to generate in the interval). Next we set the sample equation equal to y. We then plot x, y for limits set with xlim, and ylim. We then insert a grid. Finally the plot is displayed.

#RootPlots
import numpy as np
from matplotlib import pyplot as plt

x=np.linspace(0,5,100)
y=np.sin(10*x) + np.cos(3*x)
plt.plot(x,y)

plt.xlim(0,5)
plt.ylim(-5,5)
plt.grid(True)
plt.show()



Root Plot for sin 10x + cos 3x

Root Plot Program Two

The program is the same as the first, except with changes to plt.xlim() and plt.ylim(). This zooms in on the plot. It still appears there is one root at 4.25.

#RootPlots2
import numpy as np
from matplotlib import pyplot as plt

x=np.linspace(0,5,100)
y=np.sin(10*x) + np.cos(3*x)
plt.plot(x,y)

plt.xlim(3,5) #Change 0 to 3
plt.ylim(-2,2) #Change to -2 and 2
plt.grid(True)
plt.show()



Root Plot Two for sin 10x + cos 3x

Root Plot Program Three

The program is the same as the first, except with changes to plt.xlim() and plt.ylim(). This zooms in on the plot again. Note: Two roots are revealed where only one was seen before. Roots at about 4.23 and 4.27 are seen below, where only one root at 4.25 was seen above.

#RootPlots3
import numpy as np
from matplotlib import pyplot as plt

x=np.linspace(4,5,100) #Change to 4
y=np.sin(10*x) + np.cos(3*x)
plt.plot(x,y)

plt.xlim(4.2,4.3) #Change to 4.2 to 4.3
plt.ylim(-.15,.15) #Change to -.15,.15
plt.grid(True)
plt.show()



Root Plot Three for sin 10x + cos 3x








Introduction to Engineering Python: For First Year Engineering Students