-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlu_decomposition_solverExplained.py
More file actions
187 lines (150 loc) · 6.64 KB
/
lu_decomposition_solverExplained.py
File metadata and controls
187 lines (150 loc) · 6.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#lu_decomposition_solver
"""
# Astro Pema Software (c) 2024-25
# Code Oba Ozai - Astro Pema Software
Advantages of LU Decomposition in Real-World Applications
Performance and Efficiency:
In Python, using LU decomposition (lu_factor() and lu_solve() from the scipy library)
can speed up calculations, especially when you have to solve the system multiple times
with different result vectors B.
Instead of recalculating everything from scratch each time, LU decomposition lets you reuse the breakdown of your matrix
A, saving computational resources.
Applications in Data Science and Machine Learning:
When you’re working with data, you often need to fit models or solve systems of equations to find patterns.
For example:
In linear regression, you’re essentially solving a system where you want to minimize the difference between
predicted and actual values.
LU decomposition can optimize solving these systems quickly, especially when you’re dealing with large datasets.
Engineering and Physics Simulations:
In fields like engineering, physics, and even finance, you often need to model systems with many interacting variables.
For instance:
Structural analysis: Solving for forces and stresses in a bridge design.
Electric circuits: Determining voltages and currents in a network of components.
Using Python to set up matrices for these systems and solving them efficiently with LU decomposition
can significantly speed up simulations.
Imagine you have a dataset where you want to predict the relationship between different factors
(like sales, weather, and marketing spend). You can represent your data as a matrix:
A = np.array([[1, 2], [3, 4]])
B = np.array([5, 6])
By solving for X using LU decomposition, you can quickly find the best-fit parameters for your model.
Financial Forecasting:
In finance, you might have a system of equations representing different factors affecting your investment portfolio.
If you want to adjust your investments to maximize returns while minimizing risk, you can represent this system as
a matrix and solve it efficiently.
Pythons LU decomposition can help you quickly adjust your strategies in response to changing market conditions.
Flexibility:
The standard method (np.linalg.solve()) is great for quick, one-time solutions. But if you have a system where
A remains constant and only B changes, LU decomposition is far more efficient.
In Python, you can reuse the lu_factor() result and just change the vector B.
lu, piv = lu_factor(A)
X1 = lu_solve((lu, piv), B1)
X2 = lu_solve((lu, piv), B2)
For very large systems (think thousands of variables), LU decomposition can
handle the problem more efficiently than the standard method because it
reduces the amount of repetitive calculations.
Lets say you are designing a system for predicting energy consumption based on
several factors like temperature, time of day, and number of people in a building. Your
system might look something like this in Python:
import numpy as np
from scipy.linalg import lu_factor, lu_solve
# Matrix A (coefficients)
A = np.array([
[1, 2, 3],
[4, 2, 1],
[6, 3, 1]
])
# Different result vectors B (representing different scenarios)
B1 = np.array([10, 15, 25])
B2 = np.array([5, 7, 9])
# Use LU Decomposition
lu, piv = lu_factor(A)
solution1 = lu_solve((lu, piv), B1)
solution2 = lu_solve((lu, piv), B2)
print("Solution for scenario 1:", solution1)
print("Solution for scenario 2:", solution2)
By using LU decomposition, you only need to factorize the matrix
A once, which is highly efficient if you have multiple scenarios to analyze.
LU decomposition is a powerful tool in any Python toolkit for solving systems of equations efficiently,
is why i made it.
It shines in fields where speed and efficiency matter, like data analysis,
engineering, and financial modeling.
Leveraging Python's powerful libraries (numpy, scipy) allows you to apply these
concepts in real-world scenarios without getting bogged down by complex
mathematical notation.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.linalg import lu, lu_factor, lu_solve
from numpy.linalg import LinAlgError
def get_user_matrix(n):
"""Prompt the user to enter a matrix row by row."""
print(f"\nPlease enter the values for a {n}x{n} matrix:")
matrix = []
for i in range(n):
while True:
try:
row = input(f"Enter row {i + 1} (space-separated values): ").split()
if len(row) != n:
print(f"Error: You must enter exactly {n} values.")
continue
matrix.append([float(x) for x in row])
break
except ValueError:
print("Error: Please enter valid numbers.")
return np.array(matrix)
def get_result_vector(n):
"""Prompt the user to enter the result vector."""
print(f"\nPlease enter the values for the result vector (B) of size {n}:")
while True:
try:
vector = input("Enter space-separated values: ").split()
if len(vector) != n:
print(f"Error: You must enter exactly {n} values.")
continue
return np.array([float(x) for x in vector])
except ValueError:
print("Error: Please enter valid numbers.")
def lu_decomposition_solver(A, B):
"""Solve system using LU decomposition."""
try:
lu, piv = lu_factor(A)
solution = lu_solve((lu, piv), B)
return solution
except LinAlgError:
return None
def choose_solver():
"""Allow user to choose between different solving methods."""
print("\nChoose solving method:")
print("1. Standard method (using numpy.linalg.solve)")
print("2. LU Decomposition")
choice = input("Enter your choice (1 or 2): ")
if choice == '1':
return 'standard'
elif choice == '2':
return 'lu'
else:
print("Invalid choice. Defaulting to standard method.")
return 'standard'
def solve_linear_system(A, B, method='standard'):
"""Solve the system A * X = B using the specified method."""
if method == 'standard':
try:
return np.linalg.solve(A, B)
except LinAlgError:
return None
elif method == 'lu':
return lu_decomposition_solver(A, B)
return None
if __name__ == "__main__":
n = int(input("Enter the size of the square matrix (e.g., 2, 3, ...): "))
A = get_user_matrix(n)
B = get_result_vector(n)
# Choose solving method
method = choose_solver()
# Solve the system
solution = solve_linear_system(A, B, method)
if solution is not None:
print("\nSolution Vector X:")
print(solution)
else:
print("The system has no unique solution.")