Spaces:
Sleeping
Sleeping
File size: 2,967 Bytes
8f655b1 |
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 |
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
def lagrange_basis(x, i, x_points):
basis = 1.0
st.latex(f"L_{{{i}}}(x) = ")
for j in range(len(x_points)):
if j != i:
basis *= (x - x_points[j]) / (x_points[i] - x_points[j])
st.latex(f"\\cdot \\frac{{(x - x_{{{j}}})}}{{(x_{{{i}}} - x_{{{j}}})}} = \\frac{{({x} - {x_points[j]})}}{{({x_points[i]} - {x_points[j]})}}")
return basis
def lagrange_interpolation(x, x_points, y_points):
result = 0.0
st.header("Calculation Steps")
for i in range(len(x_points)):
with st.expander(f"Term for (x₀,y₀) = ({x_points[i]}, {y_points[i]})", expanded=True):
st.subheader(f"Calculating L_{i}({x}) * y_{i}")
col1, col2 = st.columns(2)
with col1:
st.markdown("**Basis Polynomial Calculation**")
basis = lagrange_basis(x, i, x_points)
with col2:
st.markdown("**Term Contribution**")
term = y_points[i] * basis
st.latex(f"y_{i} \\cdot L_{i}({x}) = {y_points[i]} \\times {basis:.4f} = {term:.4f}")
result += term
st.markdown(f"**Current Total**: {result:.4f}")
return result
# Streamlit UI
st.title("Lagrange Interpolation Visualizer")
st.markdown("Interactive calculator with step-by-step LaTeX visualization")
# Input section
st.sidebar.header("Input Parameters")
x_points = st.sidebar.text_input("X values (comma separated)", "1500,1600,1700,1900").split(',')
x_points = [float(x.strip()) for x in x_points]
y_points = st.sidebar.text_input("Y values (comma separated)", "1234,2345,4567,6789").split(',')
y_points = [float(y.strip()) for y in y_points]
x_target = st.sidebar.number_input("Target X value", value=1800.0)
# Main calculation
if len(x_points) != len(y_points):
st.error("X and Y values must have the same number of elements!")
else:
st.header("Interpolation Formula")
st.latex(r"P(x) = \sum_{i=0}^{n} y_i \cdot L_i(x)")
st.latex(r"L_i(x) = \prod_{\substack{j=0 \\ j \neq i}}^{n} \frac{x - x_j}{x_i - x_j}")
result = lagrange_interpolation(x_target, x_points, y_points)
st.success(f"**Final Interpolated Value**: P({x_target}) = {result:.2f}")
# Visualization
st.header("Visualization")
fig, ax = plt.subplots()
# Plot original points
ax.scatter(x_points, y_points, c='red', label='Original Data')
# Plot interpolated point
ax.scatter([x_target], [result], c='blue', s=100, label='Interpolated Point')
# Plot polynomial curve
x_vals = np.linspace(min(x_points)-50, max(x_points)+50, 400)
y_vals = [lagrange_interpolation(x, x_points, y_points) for x in x_vals]
ax.plot(x_vals, y_vals, '--', label='Interpolation Polynomial')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.legend()
st.pyplot(fig) |