np.linalg.solve finds x and y for a system of linear equations, or raises an error for a singular matrix. Solve a 2 × 2 system by Cramer's rule.
What to build
A program that solves a 2 × 2 linear system or reports that it is singular.
Requirements
- Print
det Dwith D to two decimals. - If the determinant is 0, print
singular matrix; otherwise printx = X, y = Y, each to two decimals.
Input
Line 1: a b c d, the matrix [[a, b], [c, d]]. Line 2: e f, the right-hand side.
Output
Two lines.
Constraints
All numbers are whole numbers between −1000 and 1000.
Example
Input:
2 1 1 3
3 5
Output:
det 5.00
x = 0.80, y = 1.40
Why it works
Cramer's rule writes each unknown as a ratio of two determinants; when the matrix's determinant is 0 the two equations are parallel or identical, so no single solution exists, which is the case NumPy reports as a singular matrix.
Examples
2 1 1 3 3 5
det 5.00 x = 0.80, y = 1.40
1 0 0 1 7 -2
det 1.00 x = 7.00, y = -2.00
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For ax + by = e and cx + dy = f, the determinant is ad − bc.
Hint 2
x = (e·d − b·f) ÷ det and y = (a·f − e·c) ÷ det.
Solution
Show one correct solution (try it yourself first)
a, b, c, d = map(float, input().split())
e, f = map(float, input().split())
det = a * d - b * c
print(f"det {det:.2f}")
if det == 0:
print("singular matrix")
else:
print(f"x = {(e * d - b * f) / det:.2f}, y = {(a * f - e * c) / det:.2f}")