Python - Solve the Linear Equation of Multiple Variable

Python - Solve the Linear Equation of Multiple Variable

To solve a linear equation with multiple variables in Python, you can use the numpy.linalg.solve() function. This function can solve a linear matrix equation, or system of linear scalar equations, represented in the matrix form Ax = b.

Here's how you can use it:

1. Define the Coefficient Matrix A and the Right-hand Side Vector b:

For instance, consider the system of equations:

3x + 2y = 18 x + y = 7 

This system can be represented in matrix form as:

| 3 2 | | x | = | 18 | | 1 1 | | y | | 7 | 

2. Use numpy.linalg.solve() to Solve the System:

Here's a Python code to solve the above system of equations:

import numpy as np # Coefficient matrix 'A' A = np.array([[3, 2], [1, 1]]) # Right-hand side vector 'b' b = np.array([18, 7]) # Solve the system of equations x = np.linalg.solve(A, b) print(x) 

The output will give you the values of x and y that satisfy the system of equations.

Notes:

  • Ensure that the coefficient matrix A is square (i.e., the number of equations is equal to the number of unknowns).
  • Before using solve(), you might want to check if the matrix A is invertible (has a non-zero determinant). If the determinant is zero, the system of equations might not have a unique solution.

You can check the determinant using:

det = np.linalg.det(A) if det == 0: print("The system does not have a unique solution.") else: x = np.linalg.solve(A, b) print(x) 

This way, you can solve a system of linear equations with multiple variables in Python using the numpy library.


More Tags

archlinux redirect azure-resource-manager restore egit itemsource spring-data pseudo-element jvisualvm bdd

More Programming Guides

Other Guides

More Programming Examples