Open In App

Solve Two Linear Equations Using Python Sympy

Last Updated : 19 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given two linear equations and our task is to solve them by using Python Sympy library. In this article, we will cover different approaches to solve two linear equations using Sympy.

Solve Two Linear Equations Using Sympy

Below are some of the approaches by which we can solve two linear equations using Sympy in Python:

Solving Equations with Two Variables Using solve() Function

In this example, we define two symbolic variables x and y, and two equations 2x + y = 5 and x – 3y = 7. The solve() function is then used to find the values of x and y that satisfy both equations.

Python3
from sympy import symbols, Eq, solve

# Define the symbolic variables
x, y = symbols('x y')

# Define the equations
eq1 = Eq(2*x + y, 5)
eq2 = Eq(x - 3*y, 7)

# Solve the equations
solution = solve((eq1, eq2), (x, y))
print(solution)

Output:

{x: 22/7, y: -9/7}

Solving Equations with Three Variables

In this example, we have a system of linear equations represented as an augmented matrix A, where each row corresponds to an equation and the last column represents the constants. The solve_linear_system() function is employed to find the values of x, y, and z that satisfy the system of equations.

Python3
from sympy import Matrix, solve_linear_system

x, y, z = symbols('x, y, z')
A = Matrix(((1, 1, 2, 1), (1, 2, 2, 3)))
solve_linear_system(A, x, y, z)

Output:

{x: -2*z - 1, y: 2}

Solve Two Linear Equations Using Augmented Matrix Method

In this example, we first define an augmented matrix representing a system of linear equations. Then, by transforming the augmented matrix into reduced row echelon form, we obtain the solution to the system of equations.

Python3
from sympy import Matrix

# Define the augmented matrix
augmented_matrix = Matrix([[2, 1, 5], [1, -3, 7]])

# Solve the system
reduced_row_echelon_form = augmented_matrix.rref()[0]
solution = reduced_row_echelon_form[:, -1]
print(solution)

Output:

Matrix([[22/7], [-9/7]])

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads