How To Find Zeros In Python

In this tutorial, we will learn how to find the zeros (also known as roots) of a mathematical function in Python.

A zero of a function is the point at which the function’s value is equal to zero. It is a crucial concept in various fields, particularly mathematics, and engineering, as it helps to understand the behavior of functions and solve equations.

We will be using the NumPy and SciPy libraries in Python for this purpose.

Step 1: Install the Required Libraries

To follow this tutorial, you will need the NumPy and SciPy libraries installed in your Python environment. You can install these packages using the following commands:

These libraries provide many useful mathematical functions, which make it easier for us to work with arrays and perform complex mathematical operations.

Step 2: Import Libraries

Now, let’s import the required libraries into our Python script.

Step 3: Define the Function

Let’s create a simple function for which we want to find the zeros. In this tutorial, we will create a quadratic function: f(x) = x^2 - 6x + 9.

Step 4: Find the Zero of the Function

Now, we will use the root() function from the SciPy library to find the zeros of our function. The root() function requires two arguments: the function itself and an initial guess for the root value. Here, we will provide an initial guess of x = 2.

The root() function will return an object containing information about the solution, which includes the value of the zero we are looking for (accessible through the x attribute).

Step 5: Verify the Result

To ensure that the solution is correct, we can plug the root value back into the original function and check if its output is equal to zero.

Full Code


Root:  [3.]
Function Output:  [0.]

The output indicates that the zero of the function is x = 3 and, when plugged back into the function, the output is indeed 0.


In this tutorial, we have successfully found the zeros of a function using the NumPy and SciPy libraries in Python.

This approach can be applied to more complex functions and real-life problems. Keep in mind, though, that this method may not always provide an exact solution, depending on factors like the initial guess and the function’s complexity.

However, it is still useful for effectively approximating zeros in many mathematical and engineering problems.