NumPy: Solve two equations

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 D with D to two decimals.
  • If the determinant is 0, print singular matrix; otherwise print x = 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

Example 1 · Input
2 1 1 3
3 5
Expected output
det 5.00
x = 0.80, y = 1.40
Example 2 · Input
1 0 0 1
7 -2
Expected output
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}")

Lesson: Linear algebra with NumPy →