Bird
0
0

Identify the error in this code using cg solver:

medium📝 Debug Q14 of 15
SciPy - Sparse Linear Algebra
Identify the error in this code using cg solver:
import numpy as np
from scipy.sparse.linalg import cg

A = np.array([[0, 1], [1, 0]])
b = np.array([1, 2])
x, info = cg(A, b)
print(x)
AMatrix A is not symmetric positive definite, so cg will fail.
BVector b has wrong shape.
Ccg function is not imported correctly.
DNo error; code runs fine.
Step-by-Step Solution
Solution:
  1. Step 1: Check matrix properties

    Matrix A = [[0,1],[1,0]] is symmetric but not positive definite (its eigenvalues are 1 and -1).
  2. Step 2: Understand cg requirements

    The conjugate gradient method requires A to be symmetric positive definite. Since A is not, cg will fail or not converge properly.
  3. Final Answer:

    Matrix A is not symmetric positive definite, so cg will fail. -> Option A
  4. Quick Check:

    cg needs symmetric positive definite matrix [OK]
Quick Trick: Check matrix eigenvalues before using cg [OK]
Common Mistakes:
  • Ignoring matrix definiteness
  • Assuming cg works for any symmetric matrix
  • Thinking vector shape causes error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes