Solve Pair of Nonlinear Equations

- Python Numerical Methods


Solve a Pair of Nonlinear Equations with Fsolve

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)



Min Plot




This website consists of example problems from numerical methods for engineers. The first examples apply to roots, plotting roots, maximums, mininums, and optimization problems. You have enough examples so that you become familiar with the syntax used in Python. The examples have been tested and the output of the programs are listed in the comments for each. All programs were run on Python using the PyCharm Community interface. They were run on an older laptop with 8GB of RAM. If you have never used Python, I recommend the manual Introduction to Engineering Python by Steve Larsen. It is availble on Amazon.











Introduction to Engineering Python: For First Year Engineering Students