Use Fsolve in Python

This article will explore how we can use `fsolve` to find a solution in Python. We will also be exploring the scenarios where it is used and some sample code to understand better how and when it can be used to reach a certain kind of outcome.

Let’s begin by understanding what `fsolve` is and why it is used.

the `fsolve` Function in Python

Equations are the roots of data science, and they help Data Scientists, Mathematicians, Chemical Engineers, and Physicians make sense of the various scenarios they deal with daily. Now, with computers enveloped in our everyday lives, it gets harder to solve equations based on a larger scale sequentially.

Python’s `fsolve` makes it easier for these professionals and others to solve these equations using different modules that the Python libraries offer. `fsolve` is essentially a SciPy module that returns the roots of non-linear equations.

There are various parameters that `fsolve` offers for various scenarios. These can be easily located directly from the SciPy documentation available online.

This is what the entire list of parameters for `fsolve` looks like:

Example Code:

``````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)
``````

You can find a detailed explanation for all parameters and what each entails in the SciPy documentation. We will, however, be going through a brief yet easy-to-understand summary of these parameters:

Parameter Description
`func`, callable `f(x, *args)` This is essentially the description of a function that takes one or more, possibly vector arguments, and returns a value with the same length as the argument.
`x0`, ndarray This argument signifies what the initial estimate for the roots of the function `f(x)=0` is.
`args`, tuple (optional) These are any extra arguments that may be required for the function.
`fprime`, callable `f(x, *args)` (optional) This is a function for computing the estimated value of the function’s Jacobian with the derivatives across the rows.
`full_output`, bool (optional) This returns any optional output values if a condition is satisfied or True.
`col_deriv`, bool (optional) Via this argument, you specify whether or not the Jacobian function computes the derivatives down the columns. According to the SciPy documentation, this is faster because of the absence of a transpose operation.
`xtol`, float (optional) This argument will allow the function to terminate a calculation based on the most `xtol` of the relative error between two consecutive iterated values.
`maxfev`, int (optional) This defines the maximum number of calls to the function.
`band`, tuple (optional) This is for when `fprime` is set to `None`. The Jacobi matrix is considered banded if the argument is set to a two-sequence containing the number of the sub and super diagonals within the matrix.
`epsfcn`, float (optional) If `fprime` is set to `None`, this argument will contain the suitable length of steps for the approximation of the forward difference of the Jacobian. The relative errors in the functions are assumed to be of the order of the machine precision if the `epsfcn` is less than the machine precision.
`factor`, float (optional) This argument determines the initial step bound and must be between (0.1, 100).
`diag`, sequence (optional) These N-positive entries serve as a scale factor for the variables.

Use the `fsolve` Function to Find Solutions in Python

As you can probably tell by now, `fsolve` can be used for various non-linear equations in different scenarios. Let’s explore some simple code samples to get a better grip of how `fsolve` may be used:

Find the Roots of the Equation `x+2cos(x)` With a Starting Point of -0.2

Example Code:

``````from math import cos
import scipy.optimize
def func(x):
y = x + 2*cos(x)
return y
y = scipy.optimize.fsolve(func,0.2)
print (y)
``````

In this code, we import the `cos` function from the vast `math` library in Python and `optimize` from `scipy` (source of `fsolve`). Next, we define our equation and store it in `y` in the `func` method.

After our equation is initialized correctly, we merely use `fsolve` to call on the method `(func)` containing the equation. In the second argument, we define the starting point for the equation.

The result is then stored in a variable `y`, printed for output.

The output of the code:

``````[-1.02986653]
``````

Solve an Equation With Starting Points 0 and 2

Example Code:

``````from math import cos
import scipy.optimize
def func(x):
y = [x[1]*x[0] - x[1] - 6, x[0]*cos(x[1]) - 3]
return y
x0 = scipy.optimize.fsolve(func,[0, 2])
print(x0)
``````

In this code, we follow the same steps as Code 1 by importing `cos` and `scipy.optimize` from Python’s `math` and `scipy` libraries. We continue to the next step by defining an equation in a method called `func`.

We then call this method an argument in the `fsolve` function and provide it with the two starting points, 0 and 2, which are then stored and printed in a variable called `x0`.

The output of the code:

``````[6.49943036 1.09102209]
``````

Find the Roots of the Equation `4sin(y)-4` With the Starting Point 0.3

Example Code:

``````from math import sin
import scipy.optimize
def func(y):
x= 4*sin(y) - 4
return x
x= scipy.optimize.fsolve(func,0.3)
print (x)
``````

In this example code, we import `sin` from the `math` library instead of `cos`. The structure of the code remains the same as in the examples above, where we also import `scipy.optimize` for `fsolve` and then define an equation inside a method `func`.

We call this method an argument in `fsolve` with a starting point of 0.3. The resulting value is stored in the variable `x` and printed for output.

The output of the code:

``````[1.57079633]
``````

In this article, we learned that `fsolve` is used for finding the roots of non-linear equations, about the different kinds of parameters `fsolve` can take and what each entails. Furthermore, we went through some working examples of `fsolve` and studied how it can be used in your code.

Now that you’ve gone through the theory and the practical code samples of how `fsolve` is used for deriving a solution, it is time to create code of your own to explore the workings of `fsolve` further.

We hope you find this article helpful in understanding how to use `fsolve` to solve problems in Python.

Author: Abid Ullah

My name is Abid Ullah, and I am a software engineer. I love writing articles on programming, and my favorite topics are Python, PHP, JavaScript, and Linux. I tend to provide solutions to people in programming problems through my articles. I believe that I can bring a lot to you with my skills, experience, and qualification in technical writing.