Untitled

mail@pastecode.io avatar
unknown
plain_text
17 days ago
2.4 kB
5
Indexable
Never
Web VPython 3.2
scene = canvas(background = color.white)

fixed_point = sphere(pos = vec(0,6,0), radius = 0.2, color = color.red)

L_0_spring = 6
L_0 = 10
k_spring = 4
theta_0 = 90 * pi/180 
m = 0.5
g = 9.8
rho = 1.225
C_D = 0.47 

#Ball object
ball = sphere(pos = fixed_point.pos - vec(L_0 * sin(theta_0), L_0 * cos(theta_0), 0), mass = m, v = vec(0,0,0), radius = 0.1, color = color.blue, make_trail = True)

#Spring object
spring = helix(pos = fixed_point.pos, axis = ball.pos - fixed_point.pos, radius = 0.1, color = color.orange)

ball.theta = theta_0

ball.omega = 0

ball.p = ball.mass * ball.v

A = pi * (ball.radius**2)

L = ball.pos - fixed_point.pos
spring.s = mag(L) - L_0_spring
SEi = 1/2 * k_spring * spring.s**2
work_s = 0

GEi = ball.mass * g * ball.pos.y
work_g = 0

#Spring WE graph
s_graph = graph(title = 'Work-Energy Spring', xtitle = 't', ytitle = 'W(t)')
w_s = gcurve(graph = s_graph, color = color.red)
e_s = gcurve(graph = s_graph, color = color.cyan)

#Grav WE graph
g_graph = graph(title = 'Work-Energy Gravitational', xtitle = 't', ytitle = 'W(t)')
w_g = gcurve(graph = g_graph, color = color.red)
e_g = gcurve(graph = g_graph, color = color.cyan)

#Total Energy graph
tote_graph = graph(title = 'Total Energy', xtitle = 't', ytitle = 'E(t)')
KE = gcurve(graph = tote_graph, color = color.red)
SE = gcurve(graph = tote_graph, color = color.orange)
GE = gcurve(graph = tote_graph, color = color.cyan)
tot_E = gcurve(graph = tote_graph, color = color.green)

t = 0
dt = 0.002

myrate = 1400

scene.waitfor("click")

while t < 10:
    rate(myrate)
    
    spring.axis = ball.pos - fixed_point.pos
    
    L = ball.pos - fixed_point.pos
    spring.s = L.mag - L_0_spring
    Fs = -k_spring * spring.s * L.hat
    Fg = -ball.mass * g * vec(0, 1, 0) 
    F_D = 1/2 * rho * ball.v.mag**2 * C_D * A * -ball.v.hat
    
    F = Fg + Fs + F_D
    
    ball.p = ball.p + F*dt
    ball.v = ball.p/ball.mass
    ball.pos = ball.pos + ball.v*dt
    
    K = 1/2 * ball.mass * ball.v.mag**2
    work_s = work_s + Fs.dot(ball.v) * dt
    work_g = work_g + Fg.dot(ball.v) * dt
    SEf = 1/2 * k_spring * spring.s**2
    GEf = ball.mass * g * ball.pos.y
    
    tot_energy = K + SEf + GEf
    
    w_s.plot(t, work_s)
    e_s.plot(t, SEf - SEi)
    
    w_g.plot(t, work_g)
    e_g.plot(t, GEf - GEi)
    
    SE.plot(t, K)
    GE.plot(t, SEf)
    KE.plot(t, GEf)
    tot_E.plot(t, tot_energy)
    
    t += dt
Leave a Comment