Fsolve python как работает

от admin

1. Multivariate equation

Our common equations are one-variable linear equations, such as x+3=5, which are simple and easy to solve.

  • Binary linear equations, that is, there are two unknowns in the equations, and the highest degree of the unknown is 1.
  • Two-dimensional quadratic equation system: There are two unknowns in the equation system, and the highest degree of the unknown is 2. These equations have formula solutions or shaped solutions.

However, when faced with a system of multi-variable and multi-fold equations, the solution is complicated, which is the research content of mathematicians. In order to better solve such problems, we can use python to achieve.

1.2 Example

For example, the system of multivariate multi-dimensional equations is the following, a system of quadratic equations of three variables:

The following two-dimensional quadratic equations.


The second system of equations is really complicated, so python is needed.

Two, python solution toolkit

Python has many toolkits for solving equations. E.g:

  • numpy: numpy.linalg.solve can directly solve linear equations. numpy is a very commonly used package in python, and the equations to be solved are relatively primitive.
  • scipy: from scipy.optimize import fsolve, can solve nonlinear equations, it is more convenient to use, but the solution set is not complete, you may miss some solutions (an example will be given later) scipy can be used in the fields of mathematics, science, and engineering Commonly used software packages of, which can handle interpolation, integration, optimization, relatively simple and easy to use
  • sympy: This toolkit is relatively powerful and supports symbolic calculations, high-precision calculations, equation solving, calculus, combinatorics, discrete mathematics, geometry, probability and statistics, physics and other functions. github address:https://github.com/sympy/sympy
  • sage, does not support bit operations, z3 constraint solver, and other toolkits. This article will not go into details. If you are interested, you can find the corresponding content.

This article describes in detail the methods of scipy and sympy to solve multiple equations.

Three, scipy method

3.1 Solve using scipy’s fsolve

About scipy: The following blog post gives very detailed,

We will only solve the part of the equation.

Using fsolve is relatively elementary, relatively simple and easy to operate, the code is relatively simple, just write the expression of the equation and run it. fsolve looks at the function of the least squares method to solve it approximately. Not very powerful enough, and in many cases the solution set is incomplete or cannot be solved.

For example for, First define the corresponding function:

The solution when the three formulas of the solving function are all 0, the initial value is in the brackets [0, 0, 0]

Seeing from the running results, this result is not a complete solution set. Because x, y, and z are all positive or negative. For example, 1 or -1, 3 or -3, 5 or -5, but this toolkit can only solve one solution.

3.2 Incomplete solutions

Obviously, the solution of x**2-9=0 is 3 or -3

But the program can only get a result 3, but not -3

3.3 Solutions of nonlinear equations

The simplest sin(x)=0.5, then x may be π/6 or 5π/6

The operation result is:

You can solve for π/6 or 5π/6, the initial iteration value is in the brackets.

3.4 Unable to solve

Some difficult cases cannot be solved

Failure to solve will give an error, and iteratively using the least square method will get an obvious wrong solution.

Four, sympy toolkit solution

If not installed, you can pip install sympy in teiminal. This toolkit involves support for symbolic calculation, high-precision calculation, pattern matching, drawing, equation solving, calculus, combinatorics, discrete mathematics, geometry, probability and statistics, physics, etc. Function. The function is more powerful, and the performance is better when solving equations.

4.1 Binary linear equations

This method is relatively simple, but the corresponding argument should be written in the form of symbols, x=Symbol(‘x’)

There are fractional solutions after solving:

4.2 Multiple solutions

Multiple solutions and complex number solutions

For example, in the case of multiple solutions, sympy can solve them well

4.3 Complex number solution

The complex number solution can also be solved well:

Complex number solutions can also be solved well

4.4 Nonlinear solution

For example, trigonometric functions:

The procedures can be solved well

4.5 More complicated two-dimensional quadratic equation

This question is more difficult, no matter how people do it, it is difficult to figure out, and iteratively unable to solve it with the scipy toolkit. But the powerful function of sympy can solve this equation very well.

There are four sets of real number solutions:

The complicated problem is finally solved, there are four sets of real number solutions!

Five, all codes

Other blogger articles:

General Catalogue of Blog Articles-Xing Xiangrui’s Technical Blog

Python implements logistic growth model fitting 2019-nCov confirmed number updated on February 1

Detailed explanation of support vector machine (SVM) algorithm complexity

Summary and analysis of practical problems related to probability

Basic problems of machine learning algorithms (three) integrated learning|adaboost and XGboost| EM algorithm

C++ backtracking programming summary

C++ dynamic programming algorithm programming summary (four) subset of the set | the sum (product) of the longest subsequence (matrix) | the largest submatrix

Русские Блоги

Python решает несколько уравнений с несколькими переменными или нелинейные уравнения

фон:Как использовать Python для решения многомерных многомерных уравнений или нелинейных уравнений.

Оригинальный контент, перепечатанный с указанием источника! Не использовать в коммерческих целях!

(Последняя статья о подсчете количества заражений 2019nCov с помощью python была перепечатана многими блогерами. Она была опубликована ранее. Многие блоггеры добавили новый контент на основе статьи и опубликовали обновленные прогнозы или добавили новый модуль. Ссылка на сообщение в блоге: следующее:)

содержание

1. Многомерное уравнение

1.1 Определение

Наши общие уравнения — это линейные уравнения с одной переменной, например x + 3 = 5, которые очень просто и легко решить.

  • Бинарные линейные уравнения, то есть в уравнениях есть две неизвестные, и наивысшая степень неизвестности равна 1.
  • Двумерная система квадратных уравнений: в системе уравнений есть две неизвестные, и наивысшая степень неизвестности равна 2. Уравнения такого типа имеют формульные решения или фигурные решения.

Но сталкиваясь с уравнениями с несколькими переменными, методы решения сложны и сложны, что составляет предмет исследования математиков. Чтобы лучше решить такие проблемы, мы можем использовать python для достижения.

1.2 Пример

Например, система многомерных уравнений с несколькими переменными представляет собой следующую систему квадратных уравнений с тремя переменными:

Ниже приводится двумерная система квадратных уравнений.


Вторая система уравнений действительно сложная, поэтому необходим Python.

Во-вторых, набор инструментов для решения Python

Python имеет множество инструментов для решения уравнений. Например:

  • numpy: numpy.linalg.solve может напрямую решать линейные уравнения. numpy — это очень часто используемый пакет в Python, и уравнения, которые необходимо решить, также относительно примитивны.
  • scipy: from scipy.optimize import fsolve, может решать нелинейные уравнения, его удобнее использовать, но набор решений не полный, и некоторые решения могут быть пропущены (пример будет приведен позже) scipy можно использовать в полях математики, естественных наук и инженерии. Обычно используемые программные пакеты, могут обрабатывать интерполяцию, интеграцию, оптимизацию, относительно просты и удобны в использовании.
  • sympy: Этот набор инструментов является относительно мощным, поддерживает символьные вычисления, высокоточные вычисления, решение уравнений, исчисление, комбинаторику, дискретную математику, геометрию, вероятность и статистику, физику и другие функции. адрес github:https://github.com/sympy/sympy
  • sage, не поддерживает битовые операции, решатель ограничений z3 и другие инструменты. В этой статье мы не будем вдаваться в подробности. Если вам интересно, вы можете найти соответствующий контент.

В этой статье подробно описаны методы scipy и sympy для решения нескольких уравнений.

Три, scipy метод

3.1 Решить, используя scipy fsolve

О scipy: следующее сообщение в блоге дает очень подробную информацию,https://blog.csdn.net/pipisorry/article/details/51106570

Мы решим только часть уравнения.

Использование fsolve относительно простое, относительно простое и удобное в эксплуатации, код относительно прост, просто напишите выражение уравнения и запустите его. fsolve рассматривает функцию метода наименьших квадратов для приближенного решения проблемы. Не очень мощный, во многих случаях набор решений неполный или не может быть решен.

Например для, Сначала определите соответствующую функцию:

Решение, когда все три формулы решающей функции равны 0, начальное значение находится в скобках [0, 0, 0]

Судя по результатам эксплуатации, этот результат не является полным набором решений. Потому что x, y и z положительные или отрицательные. Например, 1 или -1, 3 или -3, 5 или -5, но этот инструментарий может решить только одно решение.

3.2 Неполные решения

Очевидно, решение x ** 2-9 = 0 равно 3 или -3

Но программа может получить результат только 3, а не -3

3.3 Решения нелинейных уравнений

Простейший sin (x) = 0,5, тогда x может быть π / 6 или 5π / 6

Вы можете найти π / 6 или 5π / 6, а начальное значение итерации указано в скобках.

3.4 Невозможно решить

Некоторые сложные случаи не решаются

Неспособность решить приведет к ошибке, а итеративное использование метода наименьших квадратов приведет к явно неправильному решению.

Четыре, решение sympy toolkit

Если он не установлен, вы можете установить sympy в teiminal. Этот набор инструментов включает поддержку символьных вычислений, высокоточных вычислений, сопоставления с образцом, рисования, решения уравнений, исчисления, комбинаторики, дискретной математики, геометрии, вероятности и статистики, физики и т. Д. Функция. Функция более мощная, и производительность при решении уравнений выше.

4.1 Бинарные линейные уравнения

Этот метод относительно прост, но соответствующий аргумент должен быть записан в виде символа, x = Symbol (‘x’)

После решения есть дробные решения:

4.2 Множественные решения

Множественные решения и комплексные числовые решения

Например, в случае нескольких решений sympy может хорошо их решить.

4.3 Решение комплексных чисел

Решение комплексного числа также может быть решено очень хорошо:

Решения комплексных чисел также могут быть решены хорошо

4.4 Нелинейное решение

Например, тригонометрические функции:

Процедуры решаются хорошо

4.5 Более сложные двумерные квадратные уравнения

Этот вопрос сложнее, как бы люди его ни делали, его сложно понять и итеративно невозможно решить с помощью scipy toolkit. Но мощная функция симпи может очень хорошо решить это уравнение.

Существует четыре набора решений для действительных чисел:

Наконец-то сложная задача решена, есть четыре набора решений с действительными числами!

16. Numerical Methods using Python (scipy)¶

The core Python language (including the standard libraries) provide enough functionality to carry out computational research tasks. However, there are dedicated (third-party) Python libraries that provide extended functionality which

provide numerical tools for frequently occurring tasks

which are convenient to use

and are more efficient in terms of CPU time and memory requirements than using the code Python functionality alone.

We list three such modules in particular:

The numpy module provides a data type specialised for “number crunching” of vectors and matrices (this is the array type provided by “ numpy ” as introduced in 14-numpy.ipynb ), and linear algebra tools.

The matplotlib package (also knows as pylab ) provides plotting and visualisation capabilities (see 15-visualising-data.ipynb ) and the

scipy package (SCIentific PYthon) which provides a multitude of numerical algorithms and which is introduced in this chapter.

Many of the numerical algorithms available through scipy and numpy are provided by established compiled libraries which are often written in Fortran or C. They will thus execute much faster than pure Python code (which is interpreted). As a rule of thumb, we expect compiled code to be two orders of magnitude faster than pure Python code.

You can use the help function for each numerical method to find out more about the source of the implementation.

16.2. SciPy¶

Scipy provides many scientific computing functions and is generally complementary to the the functionality of numpy .

First we need to import scipy :

The scipy package provides information about its own structure when we use the help command:

The output is very long, so we’re showing just a part of it here:

If we are looking for an algorithm to integrate a function, we might explore the integrate package:

The following sections show examples which demonstrate how to employ the algorithms provided by scipy .

16.3. Numerical integration¶

Scientific Python provides a number of integration routines. A general purpose tool to solve integrals I of the kind

is provided by the quad() function of the scipy.integrate module.

It takes as input arguments the function f(x) to be integrated (the “integrand”), and the lower and upper limits a and b. It returns two values (in a tuple): the first one is the computed results and the second one is an estimation of the numerical error of that result.

Here is an example: which produces this output:

Note that quad() takes optional parameters epsabs and epsrel to increase or decrease the accuracy of its computation. (Use help(quad) to learn more.) The default values are epsabs=1.5e-8 and epsrel=1.5e-8 . For the next exercise, the default values are sufficient.

16.3.1. Exercise: integrate a function¶

Using scipy’s quad function, write a program that solves the following integral numerically: \(I = \int _0^1\cos(2\pi x) dx\) .

Find the analytical integral and compare it with the numerical solution.

Why is it important to have an estimate of the accuracy (or the error) of the numerical integral?

16.3.2. Exercise: plot before you integrate¶

It is good practice to plot the integrand function to check whether it is “well behaved” before you attempt to integrate. Singularities (i.e. \(x\) values where the \(f(x)\) tends towards minus or plus infinity) or other irregular behaviour (such as \(f(x)=\sin(\frac<1>\) ) close to \(x = 0\) are difficult to handle numerically.

Write a function with name plotquad which takes the same arguments as the quad command (i.e. \(f\) , \(a\) and \(b\) ) and which

(i) creates a plot of the integrand \(f(x)\) and

(ii) computes the integral numerically using the quad function. The return values should be as for the quad function.

16.4. Solving Ordinary Differential Equations (ODEs)¶

To solve an ordinary differential equation of the type $ \(\frac<\mathrmy><\mathrmt>(t) = f(t, y)\) $

with a given \(y(t_0)=y_0\) , we can use scipy ’s solve_ivp function. Here is a (self explaining) example program ( usesolve_ivp.py ) to find

given this differential equation: $ \(\frac<\mathrmy><\mathrmt>(t) = -2yt \quad \mathrm \quad y(0)=1.\) $

We have not given the solve_ivp command any guidance for which values of \(t\) we would like to know the solution \(y(t)\) : we have only specified that \(t_0 = 0\) and that we would like to know the solution between \(t_0=0\) and \(t_y=2\) . The solver itself has determined the number of required function evaluations, and returns the corresponding values in sol.t and sol.y[0] .

We can obtain more data points in a number of ways:

Читать:
Как изменять переменные скрипта в игре unity

Increase the default error tolerance. The relative tolerance ( rtol ) and absolute tolerance ( atol ) default to 1e-3 each. If we increase them, we typically enforce the use of a larger number of intermediate points:

We can also prescribe the precise locations for which we like to know the solutions \(y(t)\) :

If we use t_eval — and thus request values of the solution at particular points — solve_ivp will not generally change the way it computes the solution, but rather use interpolation to map the way it has internally computed the solution to the values of t for which we would like to know the solution. There is thus no (significant) computational penalty if we use t_eval to get smoother looking plots.

The solve_ivp command returns a OdeResult object, which we have called sol in the example above.

We have already seen that the solution can be found in sol.y and sol.t :

Because solve_ivp is designed to integrate systems of ordinary differential equations, sol.y is a matrix, where each row contains the values for one degree of freedom. In our simple example above, we only have one degree of freedom ( \(y\) ). This is the reason, why we had to use sol.y[0] to access the solution values.

Other interesting attributes of the OdeResult object are the number of function evaluations that were necessary (where the function is the function f which computes the right hand side of the ODE).

There is also a human-readable string, providing — for this example — a re-assuring message:

A machine readable status is available in the sol.status attribute (0 is good):

The solve_ivp command takes a number of optional parameters — we have already seen atol and rtol to change the default error tolerance of the integration. We can use the help command to explore these. The help string also explains the attributes of the solution object OdeResult in more detail:

16.4.1. Systems of coupled ODEs¶

We want to show one example of two first-order ODEs that are coupled. This helps to understand why the initial value y0 in the above example had to be provided in a list ( [y0] ) and why the solution is sol.y[0] rather than just sol.y .

\(p_1(t)\) be the number of rabbits and

\(p_2(t)\) be the number of foxes at a given time \(t\)

To compute the time dependence of \(p_1\) and \(p_2\) :

Assume that rabbits proliferate at a rate \(a\) . Per unit time a number \(a p_1\) of rabbits are born.

Assume that the number of rabbits is reduced by collisions with foxes: per unit time \(c p_1 p_2\) rabbits are eaten.

Assume that birth rate of foxes depends only on food intake in form of rabbits.

Assume that foxes die a natural death at a rate \(b\) .

We put this together into the system of coupled ordinary differential equations: \begin \label \frac

&=& a p_1 — c p_1 p_2\nonumber\ \frac

&=& c p_1 p_2 — b p_2\nonumber \end

We use the following parameters:

rabbit birth rate \(a = 0.7\)

rabbit-fox-collision rate \( c = 0.007\)

fox death rate \(b = 1\)

We want to solve this for \(p_1(t_0)=70\) and \(p_2(t_0)=50\) as initial values, starting at \(t_0=0\) for 30 units of time.

16.5. Root finding¶

If you try to find a \(x\) such that $ \(f(x)=0\) \( then this is called *root finding*. Note that problems like \) g(x)=h(x) \( fall in this category as you can rewrite them as \) f(x)=g(x)−h(x)=0$.

A number of root finding tools are available in scipy ’s optimize module.

16.5.1. Root finding using the bisection method¶

First we introduce the bisect algorithm which is (i) robust and (ii) slow but conceptually very simple.

Suppose we need to compute the roots of f(x)=x 3 − 2x 2 . This function has a (double) root at x = 0 (this is trivial to see) and another root which is located between x = 1.5 (where f(1.5)= − 1.125) and x = 3 (where f(3)=9). It is pretty straightforward to see that this other root is located at x = 2. Here is a program that determines this root numerically:

The bisect() method takes three compulsory arguments: (i) the function f(x), (ii) a lower limit a (for which we have chosen 1.5 in our example) and (ii) an upper limit b (for which we have chosen 3). The optional parameter xtol determines the maximum error of the method.

One of the requirements of the bisection method is that the interval [a, b] has to be chosen such that the function is either positive at a and negative at b, or that the function is negative at a and postive at b. In other words: a and b have to enclose a root.

16.5.2. Exercise: root finding using the bisect method¶

Write a program with name sqrttwo.py to determine an approximation of \(\sqrt<2>\) by finding a root x of the function \(f(x)=2 − x^2\) using the bisection algorithm. Choose a tolerance for the approximation of the root of 10 −8 .

Document your choice of the initial bracket \([a, b]\) for the root: which values have you chosen for a and for b and why?

Study the results:

Which value for the root x does the bisection algorithm return?

Compute the value of \(\\sqrt<2>\) using math.sqrt(2) and compare this with the approximation of the root. How big is the absolute error of x? How does this compare with xtol ?

16.5.3. Root finding using the fsolve funcion¶

A (often) better (in the sense of “more efficient”) algorithm than the bisection algorithm is implemented in the general purpose fsolve() function for root finding of (multidimensional) functions. This algorithm needs only one starting point close to the suspected location of the root (but is not garanteed to converge).

Here is an example:

The return value[6] of fsolve is a numpy array of length n for a root finding problem with n variables. In the example above, we have n = 1.

16.6. Interpolation¶

Given a set of N points \((x_i, y_i)\) with \(i = 1, 2, …N\) , we sometimes need a function \(\hat(x)\) which returns \(y_i = f(x_i)\) where \(x == x_i\) , and which in addition provides some interpolation of the data \((x_i, y_i)\) for all \(x\) .

The function y0 = scipy.interpolate.interp1d(x,y,kind=’nearest’) does this interpolation based on splines of varying order. Note that the function interp1d returns a function y0 which will then interpolate the x-y data for any given \(x\) when called as \(y0(x)\) .

The code below demonstrates this, and shows the different interpolation kinds.

16.7. Curve fitting¶

We have already seen in the numpy chapter that we can fit polynomial functions through a data set using the numpy.polyfit function. Here, we introduce a more generic curve fitting algorithm.

Scipy provides a somewhat generic function (based on the Levenburg-Marquardt algorithm )through scipy.optimize.curve_fit to fit a given (Python) function to a given data set. The assumption is that we have been given a set of data with points \(x_1, x_2, …x_N\) and with corresponding function values \(y_i\) and a dependence of \(y_i\) on \(x_i\) such that \(y_i=f(x_i,\vec

)\) . We want to determine the parameter vector \(\vec

=(p_1, p_2, \ldots, p_k)\) so that \(r\) , the sum of the residuals, is as small as possible:

\[r = \sum\limits_^N \left(y_i — f(x_i, \vec

)\right)^2\]

Curve fitting is of particular use if the data is noisy: for a given \(x_i\) and \(y_i=f(x_i,\vec

)\) we have a (unknown) error term \(\epsilon_i\) so that \(y_i=f(x_i,\vec

)+\epsilon_i\) .

We use the following example to clarify this: $ \(f(x,\vec

) = a \exp(-b x) + c, \quad\mathrm\quad \vec

=\mathtt\) $

Note that in the source code above we define the fitting function \(y = f(x)\) through Python code. We can thus fit (nearly) arbitrary functions using the curve_fit method.

The curve_fit function returns a tuple popt, pcov . The first entry popt contains a tuple of the OPTimal Parameters (in the sense that these minimise equation ([eq:1]). The second entry contains the covariance matrix for all parameters. The diagonals provide the variance of the parameter estimations.

For the curve fitting process to work, the Levenburg-Marquardt algorithm needs to start the fitting process with initial guesses for the final parameters. If these are not specified (as in the example above), the value “1.0“ is used for the initial guess.

If the algorithm fails to fit a function to data (even though the function describes the data reasonably), we need to give the algorithm better estimates for the initial parameters. For the example shown above, we could give the estimates to the curve_fit function by changing the line

if our initial guesses would be a = 2, b = 1 and c = 0.6. Once we take the algorithm “roughly in the right area” in parameter space, the fitting usually works well.

16.8. Fourier transforms¶

In the next example, we create a signal as a superposition of a 50 Hz and 70 Hz sine wave (with a slight phase shift between them). We then Fourier transform the signal and plot the absolute value of the (complex) discrete Fourier transform coefficients against frequency, and expect to see peaks at 50Hz and 70Hz.

The lower plot shows the discrete Fourier transform computed from the data shown in the upper plot.

16.9. Optimisation¶

Often we need to find the maximum or minimum of a particular function f(x) where f is a scalar function but x could be a vector. Typical applications are the minimisation of entities such as cost, risk and error, or the maximisation of productivity, efficiency and profit. Optimisation routines typically provide a method to minimise a given function: if we need to maximise f(x) we create a new function g(x) that reverses the sign of f, i.e. g(x)= − f(x) and we minimise g(x).

Below, we provide an example showing (i) the definition of the test function and (ii) the call of the scipy.optimize.fmin function which takes as argument a function f to minimise and an initial value x0 from which to start the search for the minimum, and which returns the value of x for which f(x) is (locally) minimised. Typically, the search for the minimum is a local search, i.e. the algorithm follows the local gradient. We repeat the search for the minimum for two values (x0 = 1.0 and x0 = 2.0, respectively) to demonstrate that depending on the starting value we may find different minimar of the function f.

The majority of the commands (after the two calls to fmin ) in the file fmin1.py creates the plot of the function, the start points for the searches and the minima obtained:

Calling the fmin function will produce some diagnostic output, which you can also see above.

Return value of fmin

Note that the return value from the fmin function is a numpy array which – for the example above – contains only one number as we have only one parameter (here x) to vary. In general, fmin can be used to find the minimum in a higher-dimensional parameter space if there are several parameters. In that case, the numpy array would contain those parameters that minimise the objective function. The objective function \(f(x)\) has to return a scalar even if there are more parameters, i.e. even if \(x\) is a vector as in \(f(\mathbf)\) .

16.10. Other numerical methods¶

Scientific Python and Numpy provide access to a large number of other numerical algorithms including function interpolation, Fourier transforms, optimisation, special functions (such as Bessel functions), signal processing and filters, random number generation, and more. Start to explore scipy ’s and numpy ’s capabilities using the help function and the documentation provided on the web.

16.11. scipy.io: Scipy-input output¶

Scipy provides routines to read and write Matlab mat files. Here is an example where we create a Matlab compatible file storing a (1×11) matrix, and then read this data into a numpy array from Python using the scipy Input-Output library:

First we create a mat file in Octave (Octave is [mostly] compatible with Matlab):

scipy.optimize.fsolve#

Return the roots of the (non-linear) equations defined by func(x) = 0 given a starting estimate.

Parameters : func callable f(x, *args)

A function that takes at least one (possibly vector) argument, and returns a value of the same length.

x0 ndarray

The starting estimate for the roots of func(x) = 0 .

args tuple, optional

Any extra arguments to func.

fprime callable f(x, *args) , 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.

Returns : x ndarray

The solution (or the result of the last iteration for an unsuccessful call).

infodict dict

A dictionary of optional outputs with the keys:

number of function calls

number of Jacobian calls

function evaluated at the output

the orthogonal matrix, q, produced by the QR factorization of the final approximate Jacobian matrix, stored column wise

upper triangular matrix produced by QR factorization of the same matrix

the vector (transpose(q) * fvec)

ier int

An integer flag. Set to 1 if a solution was found, otherwise refer to mesg for more information.

mesg str

If no solution is found, mesg details the cause of failure.

Interface to root finding algorithms for multivariate functions. See the method=’hybr’ in particular.

fsolve is a wrapper around MINPACK’s hybrd and hybrj algorithms.

Find a solution to the system of equations: x0*cos(x1) = 4,   x1*x0 — x1 = 5 .

Похожие статьи