import streamlit as st import numpy as np import pandas as pd # --- Page Setup --- st.set_page_config(layout="wide") st.title("Linear Equation Solver (for N Variables)") st.write(""" This app solves a system of N linear equations in the form **Ax = B**. - **A** is the matrix of your known coefficients. - **x** is the vector of your unknown variables (e.g., x1, x2, ... x12). - **B** is the vector of your known constants. """) # --- Sidebar for Inputs --- st.sidebar.header("1. Set Up Your System") N = st.sidebar.number_input( "How many variables (N)?", min_value=2, value=3, # Default to 3 for a simple example step=1, help="This is the 'N' in your NxN system. You can set this to 12." ) st.sidebar.info(f"You are solving for **{N}** unknown variables (from x1 to x{N}).") # --- Main Area for Data Entry --- st.header(f"2. Enter Your {N}x{N} System") st.write("Use the tables below to build your **A** matrix (coefficients) and **B** vector (constants).") # Create two columns for A (left) and B (right) col1, col2 = st.columns([3, 1]) # Make column 1 three times wider # --- Matrix A Input (Coefficients) --- with col1: st.subheader("Coefficients (Matrix A)") # Create column names like 'x1', 'x2', ... col_names = [f"x{i+1}" for i in range(N)] # Create row names like 'Eq 1', 'Eq 2', ... row_names = [f"Eq {i+1}" for i in range(N)] # Initialize an NxN identity matrix as a default (1s on the diagonal) # This is just a placeholder so the table isn't empty A_df = pd.DataFrame(np.identity(N), columns=col_names, index=row_names) # Use st.data_editor to get user input in a table A_input = st.data_editor(A_df) # --- Vector B Input (Constants) --- with col2: st.subheader("Constants (Vector B)") # Initialize an Nx1 zero vector as a default B_df = pd.DataFrame(np.zeros((N, 1)), columns=["Value"], index=row_names) # Use st.data_editor for the constants B_input = st.data_editor(B_df) # --- Solve Button --- st.header("3. Solve the System") if st.button(f"Solve for {N} Variables", type="primary"): # Get the final values from the tables as numpy arrays A = A_input.values B = B_input.values.flatten() # .flatten() turns the [N, 1] column into a 1D vector try: # --- THE CORE CALCULATION --- # This one line solves the entire system! x = np.linalg.solve(A, B) st.success("✅ System solved successfully!") # --- Display Solution --- st.subheader("Solution (Vector x)") st.write("These are the values for your unknown variables:") # Use pandas for a nice table solution_df = pd.DataFrame( x, index=[f"x{i+1}" for i in range(N)], columns=["Solved Value"] ) # Display solution in two ways: table and bar chart sol_col1, sol_col2 = st.columns(2) with sol_col1: st.write("**Tabular Form:**") st.dataframe(solution_df, use_container_width=True) with sol_col2: st.write("**Visual Help (Bar Chart):**") st.bar_chart(solution_df) # --- Verification (Visual Help) --- st.subheader("Verification (Checking the Answer)") st.write(""" To check the answer, we multiply your **A** matrix by our new solution **x**. The result (**A*x**) should be identical to your original **B** vector. """) verification = np.dot(A, x) # Create a comparison table verify_df = pd.DataFrame({ "Your Original 'B'": B, "Calculated 'A*x'": verification, "Difference": B - verification }, index=row_names) st.dataframe(verify_df, use_container_width=True) st.caption("Note: The 'Difference' column should be extremely small (e.g., 1.0e-15), which is the computer's way of saying zero.") except np.linalg.LinAlgError: # This happens if the system has no unique solution st.error("Error: This system cannot be solved.") st.write(""" This usually means the equations are dependent (e.g., one equation is a multiple of another) or inconsistent. The matrix **A** is 'singular', meaning it has no unique solution. """)