In fields such as data analysis and scientific computing, situations often arise where you need to solve equations with multiple variables (systems of linear equations). By using NumPy, a numerical computing library for Python, you can implement these calculations efficiently with a minimal amount of code.
This article explains how to solve systems of linear equations using the numpy.linalg.solve function and how to verify the calculation results.
Definition of Linear Equations and Representation in NumPy
As a concrete example, let’s consider a system of equations with two variables. Imagine a scenario where you need to calculate the individual prices of Adult and Child tickets for an amusement park based on the total price of group orders.
Example Equations
- A group of 3 Adults and 2 Children pays a total of 3800 USD.
- A group of 1 Adult and 3 Children pays a total of 2200 USD.
Organizing this into a text-based mathematical formula looks like this:
3x + 2y = 3800 1x + 3y = 2200
When handling these equations in a matrix format, we decompose them into a coefficient matrix and a dependent vector (constants).
- Coefficient Matrix (Coefficients on the left side):
[[3, 2], [1, 3]] - Dependent Vector (Values on the right side):
[3800, 2200]
Implementation Using numpy.linalg.solve
By using the solve function included in NumPy’s linalg module, you can find the solution (x, y) simply by passing the coefficient matrix and the dependent vector.
Below is the complete Python code to solve the equations defined above.
import numpy as np
def solve_ticket_prices():
"""
Function to solve a system of linear equations using NumPy.
Scenario: Calculating ticket prices.
Equation 1: 3 * Adult + 2 * Child = 3800
Equation 2: 1 * Adult + 3 * Child = 2200
"""
# Coefficient Matrix (2x2)
# Row 0: 3 Adults, 2 Children
# Row 1: 1 Adult, 3 Children
coefficient_matrix = np.array([
[3, 2],
[1, 3]
])
# Dependent Vector (Total prices)
dependent_values = np.array([3800, 2200])
# Solve the system of linear equations
# The solution is stored in the order [x, y] (Adult, Child)
solution = np.linalg.solve(coefficient_matrix, dependent_values)
# Display results
print("--- Calculation Result ---")
print(f"Adult Ticket Price (x): {solution[0]}")
print(f"Child Ticket Price (y): {solution[1]}")
return coefficient_matrix, solution, dependent_values
def verify_solution(coef_matrix, sol, dep_values):
"""
Function to verify if the calculated solution is correct.
Checks if (Coefficient Matrix) x (Solution) matches (Dependent Vector).
"""
# Calculate dot product: Check if Ax = b
calculated_values = np.dot(coef_matrix, sol)
print("\n--- Verification ---")
print(f"Result of substitution: {calculated_values}")
print(f"Original dependent vector: {dep_values}")
# Check for numerical approximation (considering floating-point errors)
# Returns True if two arrays are element-wise equal within a tolerance.
is_correct = np.allclose(calculated_values, dep_values)
print(f"Verification Result: {'Correct' if is_correct else 'Incorrect'}")
if __name__ == "__main__":
# Solve the equations
coef, sol, dep = solve_ticket_prices()
# Verify the solution
verify_solution(coef, sol, dep)
Explanation of the Code
- Defining the Coefficient Matrix: Use
np.arrayto define the coefficients associated with the variables (x, y) as a 2-dimensional array. - Defining the Dependent Vector: Define the values on the right side of the equations as a 1-dimensional array.
- Calculating the Solution: Calling
np.linalg.solve(A, b)returns the solution vectorxthat satisfiesAx = b.
Confirming Calculation Precision (Verification)
To check if the obtained solution is correct, you calculate the matrix product (dot product) of the original coefficient matrix and the solution vector, then check if it matches the original dependent vector.
In the code above, the np.dot function is used for verification. Also, since floating-point calculations may contain minute errors, it is common practice to use np.allclose to judge whether values are “numerically close enough” rather than checking for exact equality.
Execution Result
--- Calculation Result ---
Adult Ticket Price (x): 1000.0
Child Ticket Price (y): 400.0
--- Verification ---
Result of substitution: [3800. 2200.]
Original dependent vector: [3800 2200]
Verification Result: Correct
As shown, by using NumPy, you can solve systems of linear equations without needing to worry about complex matrix operations. Even for systems with three or more variables, you can process them using the same procedure simply by expanding the size of the matrices.
