pendulum / app.py
jcmachicao's picture
Update app.py
b5ef362 verified
raw
history blame
1.78 kB
import streamlit as st
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
class Pendulum:
def __init__(self, length, gravity):
self.L = length
self.g = gravity
def derivatives(self, state, t):
theta, omega = state
dydt = [omega, -self.g/self.L * np.sin(theta)]
return dydt
def simulate(self, initial_angle, duration, time_points):
initial_state = [initial_angle, 0] # angle and angular velocity
t = np.linspace(0, duration, time_points)
solution = odeint(self.derivatives, initial_state, t)
return t, solution
def main():
st.title("Simulación Simple del Mecanismo del Péndulo")
# User inputs
length = st.slider("Amplitud del Péndulo (m)", 0.1, 5.0, 1.0)
initial_angle = st.slider("Angulo Inicial (grados)", -90.0, 90.0, 45.0)
# Convert to radians
initial_angle_rad = np.deg2rad(initial_angle)
# Create and simulate pendulum
pendulum = Pendulum(length=length, gravity=9.81)
t, solution = pendulum.simulate(initial_angle_rad, duration=10, time_points=1000)
# Plot results
fig, ax = plt.subplots()
ax.plot(t, np.rad2deg(solution[:, 0]))
ax.set_xlabel('Tiempo (s)')
ax.set_ylabel('Angulo (grados)')
ax.grid(True)
st.pyplot(fig)
# Display energy conservation
E_kinetic = 0.5 * length * solution[:, 1]**2
E_potential = 9.81 * length * (1 - np.cos(solution[:, 0]))
E_total = E_kinetic + E_potential
st.write("### Conservación de la Energía")
st.line_chart({"Energía Total": E_total,
"Energía Cinética": E_kinetic,
"Energía Potencial": E_potential})
if __name__ == "__main__":
main()