When doing numerical calculations, there is a good chance to solve nonlinear simultaneous equations. Many years ago, when I was a graduate student doing research, I implemented it in Fortran. Recently, I have more opportunities to write programs in Python, and I have come across the situation of solving nonlinear simultaneous equations again. Newton's method is a well-known method for solving nonlinear simultaneous equations, but I searched for a good library because it is troublesome to implement from scratch.
It was easy, not odd. This time, I would like to solve the following nonlinear simultaneous equations as an example.
The source code is as follows. I will give a brief explanation later.
import numpy as np
from scipy import optimize
#Return the function you want to solve in a list
def func(x):
return [x[0]**2 + x[1]**2 -1.0,
x[0]]
result = optimize.root( func, [ 1.0, 0.0], method="broyden1")
print(result)
The execution result is as follows.
fun: array([-1.98898568e-07, -5.14009858e-06])
message: 'A solution was found at the specified tolerance.'
nit: 9
status: 1
success: True
x: array([-5.14009858e-06, 9.99999901e-01])
See the scipy documentation (https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.root.html) for more information on how to use scipy.optimize.root. Here is a rough explanation. The first argument of optimize.root is the func function that defines the function you want to solve. The second argument is the initial value to use when starting to solve the problem. The third argument is where you specify how to solve. For details, please refer to scipy documentation, but here is one caveat. .. This time, broyden1 is specified in method, but depending on the argument, the Jacobian matrix needs to be defined separately. I was too lazy to choose one that didn't require a Jacobian procession.
Also, the important part about the execution result is the part of x: array (), which represents the actual solution, and it seems that it looks like $ x = 0, y = 1 $. See scipy.optimize.OptimizeResult for solution details.
Python is convenient because it can be easily implemented in various ways. I wanted to meet when I was a graduate student. No, I met him, but it was troublesome to change trains, so I pretended not to see it. sorry.
Recommended Posts