In this example we will solve a pair of nonlinear equations using fsolve. We will solve for one set of coordinates, which represents one intersection of the two plots. There can be more that one intersection, and more than one set of coordinates that is a solution. Suggested reading is Numerical Methods for Engineers, Fifth Edition by Chapra and Canale.
Plot and solve this pair of nonlinear equations with fsolve: x+y^2 = 4 and e^x+ xy = 3
Import scipy.optimize import fsolve, import math for the exp, import numpy and matplotlib for the plot. Define the variables and the equations in the function. Use fsolve to call the functions, and enter the initial guess. Print the results of fsolve. As part of the same program we will be plotting the pair of equations. Use np.arange for initial, final, and step interval for x . Next we list the two y equations. The y and y1 equations will use the same x values from np.arange. We then plot plt.plot(x, y,) , and plt.plot(x, y1, dashes=[6,2]) . Next is graph title. Then we set limits for the y axis. Dashes are used for the y1 plot. Finally a grid is shown on the plot, and the plots are displayed.
#Solve this pair of nonlinear equations with fsolve
# x+y^2 = 4
# e^x+ xy = 3
from scipy.optimize import fsolve
from math import exp
import numpy as np
import matplotlib.pyplot as plt
def equations(vars):
x, y = vars
eq1 = x+y**2-4
eq2 = exp(x) + x*y - 3
return [eq1, eq2]
#Initial guess x=1, y=1
x, y = fsolve(equations, (1, 1))
print(x, y)
x = np.arange(-2, 2, 0.01)
y = (4-x)**.5
y1= (3 - np.exp(x))/x
plt.title("Plot of two nonlinear equations")
plt.ylim(0,5) #To keep plots in range
plt.plot(x, y,)
plt.plot(x, y1, dashes=[6,2]) #To show one plot as dashes
plt.grid()
plt.show()
#Output: 0.6203445234801195 1.8383839306750887
#Intersection point at (x,y)