Python SciPy Tutorial

Chưa phân loại
In this lesson, we will see what is the use of SciPy library in Python and how it helps us to work with mathematical equations and algorithms in an interactive manner. The good thing about SciPy Python package is that if we want classes or construct web pages, SciPy is fully compatible with the system as a whole and can provide seamless integration.

As SciPy is open source, it has a very active and vibrant community of developers due to which there are enormous number of modules present for a vast amount of scientific applications and calculations available with SciPy. Some of the complex mathematical operations which can be performed with SciPy are:

  • Interpolation
  • Integration
  • Optimization
  • Image processing
  • Statistics
  • Special function calculations etc.

SciPy can be compared to most command and standard libraries like GSL library for C++ and Matlab. As SciPy is built on top of NumPy package, these two packages can be integrated completely as well. If you can think of a mathematical operation which needs to be done, make sure you check SciPy library before you implement that module on your own because in most cases, SciPy have all the operations for you fully implemented already.

Install SciPy Library

Let’s install SciPy library before we move to the actual examples and concepts. There are two ways to install this package. First one includes using the Python package manager, pip:

pip install scipy

The second way relates to Anaconda, we can install the package as:

conda install -c anaconda scipy

Once the library is installed, we can import it as:

import scipy

Finally, as we will be using NumPy as well (It is recommended that for all NumPy operations, we use NumPy directly instead of going through the SciPy package):

import numpy

It is possible that in some cases, we will also like to plot our results for which we will use the Matplotlib library. Perform the following import for that library:

import matplotlib

I will be using the Anaconda manager for all the examples in this lesson. I will launch a Jupyter Notebook for the same:

Now that we are ready with all the import statements to write some code, let’s start diving into SciPy package with some practical examples.

Working with Polynomial Equations

We will start by looking at simple Polynomial equations. There are two ways with which we can integrate Polynomial functions into our program. We can make use of poly1d class which makes use of coefficients or the roots of a polynomial for initialising a polynomial. Let’s look at an example:

from numpy import poly1d
first_polynomial = poly1d([3, 4, 7])

When we run this example, we will see the following output:

Clearly, the polynomial representation of the equation is printed as the output so that the result is pretty easy to understand. We can perform various operations on this polynomial as well, like square it, find its derivative or even solve it for a value of x. Let’s try doing all of these in the next example:

print("Polynomial Square: n")
print(first_polynomial * first_polynomial)

print("Derivative of Polynomial: n")

print("Solving the Polynomial: n")

When we run this example, we will see the following output:

Just when I was thinking that this is all we could do with SciPy, I remembered that we can integrate a Polynomial as well. Let’s run a final example with Polynomials:

print("Integrating the Polynomial: n")

The integer we pass tells the package how many times to integrate the polynomial:

We can simply pass another integer which tells the package how many times to integrate this polynomial.

Solving Linear Equations

It is even possible to solve linear equations with SciPy and find their roots, if they exist. To solve linear equations, we represent the set of equations as NumPy arrays and their solution as a separate NumPy arrays. Let’s visualise it with an example where we do the same and make use of linalg package to find the roots of the equations, here are the equations we will be solving:

1x + 5y = 6
3x + 7y = 9

Let’s solve the above equations:

from scipy import linalg

equation = np.array([[1, 5], [3, 7]])
solution = np.array([[6], [9]])

roots = linalg.solve(equation, solution)

print("Found the roots:")

print("n Dot product should be zero if the solutions are correct:")
print( – solution)

When we run the above program, we will see that the dot product equation gives zero result, which means that the roots which the program found were correct:

Fourier Transformations with SciPy

Fourier Transformations helps us to express a function as separate components that make up that function and guides us about the way through which we can recombine those components to get the original function back.

Let’s look at a simple example of Fourier Transformations where we plot the sum of two cosines using the Matplotlib library:

from scipy.fftpack import fft

# Number of sample points
N = 500

# sample spacing
T = 1.0 / 800.0
x = np.linspace(0.0, N*T, N)
y = np.cos(50.0 * 2.0* np.pi * x) + 0.5 * np.cos(80.0 * 2.0 * np.pi * x)
yf = fft(y)
xf = np.linspace(0.0, 1.0/(2.0 * T), N//2)

# matplotlib for plotting purposes
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))

plt.ylabel(‘Y axis’)
plt.xlabel(‘X axis’)


Here, we started by constructing a sample space and cosine equation which we then transformed and plotted. Here is the output of the above program:

This is one of the good example where we see SciPy being used in a complex mathematical equation to visualise things easily.

Vectors and Matrix with SciPy

Now that we know a lot of things which SciPy is capable of, we can be sure that SciPy can also work with Vectors and Matrix. The matrices are an important part of linear algebra as matrices is something we use to represent Vector mappings as well.

Just like we looked at solving linear equations with SciPy, we can represent vectors with np.array() functions. Let’s start by constructing a matrix:

my_matrix = np.matrix(np.random.random((3, 3)))

Here is the output of the above snippet:

Whenever we talk about matrices, we always talk about Eigenvalues and Eigenvectors. To put in simple words, Eigenvectors are the vectors which, when multiplied with a matrix, do not change their direction, as opposed to most of the vectors. This means that even when you multiply an Eigenvectors with a matrix, there exists a value (or eigenvalue) which is one of the factor of the multiplication. This means:

Ax = λx.

In above equation, A is the matrix, λ is the Eigenvalue and x is the Vector. Let’s write a simple code snippet to find the Eigenvalues for a given Vector:

la, vector = linalg.eig(my_matrix)

print(vector[:, 0])
print(vector[:, 1])


When we run this example, we will see the following output:

Calculating Matrix Determinant

The next operation we will carry out with SciPy is to calculate the determinant of a 2-dimensional matrix. We will reuse the matrix we used in the last code snippet here:

linalg.det( my_matrix )

When we run this example, we will see the following output:


In this lesson, we looked at a lot of good examples where SciPy can help us by carrying out complex mathematical computations for us with an easy to use API and packages.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Hướng dẫn cài đặt TIG stack (Telegraf – InfluxDB – Grafana)

Trong tất cả các công cụ giám sát hiện đại hiện có thì có lẽ TIG stack (Telegraf, InfluxDB...

[CentOS 8] Hướng dẫn cài đặt LAMP Stack trên CentOS 8

LAMP Stack là viết tắt của Linux, Apache, MariaDB và PHP. Nó được sử dụng rộng rãi nhất để lưu...

5 Best Linux Offensive Security Distributions

This is not a tutorial but a brief review on the most popular Linux distributions oriented to (offensive) IT security....
Bài Viết

Bài Viết Mới Cập Nhật


Mua Proxy v6 US Private chạy PRE, Face, Insta, Gmail

Mua shadowsocks và hướng dẫn sữ dụng trên window

Tại sao Proxy Socks lại được ưa chuộng hơn Proxy HTTP?

Mua thuê proxy v4 nuôi zalo chất lượng cao, kinh nghiệm tránh quét tài khoản zalo