How to solve a circulant matrix equation using Python SciPy?

ScipyScientific ComputingProgramming

The linear function named scipy.linalg.solveh_banded is used to solve the banded matrix equation. In the below given example we will be solving the circulant system Cx = b −

Example

from scipy.linalg import solve_circulant, solve, circulant, lstsq
import numpy as np
c = np.array([2, 2, 4])
b = np.array([1, 2, 3])
solve_circulant(c, b)

Output

array([ 0.75, -0.25, 0.25])

Example

Let’s see a singular example, it will raise an LinAlgError −

from scipy.linalg import solve_circulant, solve, circulant, lstsq
import numpy as np
c = np.array([1, 1, 0, 0])
b = np.array([1, 2, 3, 4])
solve_circulant(c, b)

Output

--------------------------------------------------------------------------

LinAlgError Traceback (most recent call last)
<ipython-input-6-978604ed0a97> in <module>
----> 1 solve_circulant(c, b)

~\AppData\Roaming\Python\Python37\site-packages\scipy\linalg\basic.py in
solve_circulant(c, b, singular, tol, caxis, baxis, outaxis)
865    if is_near_singular:
866       if singular == 'raise':
--> 867     raise LinAlgError("near singular circulant matrix.")
868    else:
869    # Replace the small values with 1 to avoid errors in the
LinAlgError: near singular circulant matrix.

Now, to remove this error we need to use the option singular = ‘lstsq’ as follows −

from scipy.linalg import solve_circulant, solve, circulant, lstsq
import numpy as np
c = np.array([1, 1, 0, 0])
b = np.array([1, 2, 3, 4])
solve_circulant(c, b, singular='lstsq')

Output

array([0.25, 1.25, 2.25, 1.25])
raja
Updated on 24-Nov-2021 11:53:49

Advertisements