SciPy 4

SciPy: fsolve

SciPy: fsolve-2

We can solve the nonlinear equation by Jacobian determinant(matrix). For the question in fsolve-1, the Jacobian matrix of f to u is :
$$
\begin{bmatrix}
\frac{\partial f_1} {\partial u_1} \frac{\partial f_1} {\partial u_2} \frac{\partial f_1} {\partial u_3} \\
\frac{\partial f_2} {\partial u_1} \frac{\partial f_2} {\partial u_2} \frac{\partial f_2} {\partial u_3} \\
\frac{\partial f_3} {\partial u_1} \frac{\partial f_3} {\partial u_2} \frac{\partial f_3} {\partial u_3} \\
\end{bmatrix}
$$

We use the fprime parameter to transfer the Jacobian matrix to fsolve.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# -*- coding: utf-8 -*-
from scipy.optimize import fsolve
import numpy as np

def f(x):
x0 = float(x[0])
x1 = float(x[1])
x2 = float(x[2])
return [
5*x1+3,
4*x0**2-2*np.sin(x1*x2),
x1*x2-1.5
]

def j(x):
x0 = float(x[0])
x1 = float(x[1])
x2 = float(x[2])
return [
[0, 5, 0],
[8*x0, -2*x2*np.cos(x1*x2), -2*x1*np.cos(x1*x2)],
[0, x2, x1]
]

result = fsolve(f, [1,1,1], fprime=j)

print(result)
print(f(result))

The Result :

1
2
[-0.70622057 -0.6        -2.5       ]
[0.0, -9.1260332624187868e-14, 5.329070518200751e-15]

The definition of fsolve :

scipy.optimize.fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn=None, factor=100, diag=None)

func : callable f(x, args)
A function that takes at least one (possibly vector) argument.
x0 : ndarray
The starting estimate for the roots of func(x) = 0.
args : tuple, optional
Any extra arguments to func.
fprime : callable(x), optional
A function to compute the Jacobian of func with derivatives across the rows. By default, the Jacobian will be estimated.
full_output : bool, optional
If True, return optional outputs.
col_deriv : bool, optional
Specify whether the Jacobian function computes derivatives down the columns (faster, because there is no transpose operation).
xtol : float, optional
The calculation will terminate if the relative error between two consecutive iterates is at most xtol.
maxfev : int, optional
The maximum number of calls to the function. If zero, then 100
(N+1) is the maximum where N is the number of elements in x0.
band : tuple, optional
If set to a two-sequence containing the number of sub- and super-diagonals within the band of the Jacobi matrix, the Jacobi matrix is considered banded (only for fprime=None).
epsfcn : float, optional
A suitable step length for the forward-difference approximation of the Jacobian (for fprime=None). If epsfcn is less than the machine precision, it is assumed that the relative errors in the functions are of the order of the machine precision.
factor : float, optional
A parameter determining the initial step bound (factor * || diag * x||). Should be in the interval (0.1, 100).
diag : sequence, optional
N positive entries that serve as a scale factors for the variables.


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!