Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.4 kB
8
Indexable
Never
Web VPython 3.2
scene = canvas(background = color.white)
l_0 = 0.5
k = 150

obj_1 = sphere(pos = vec(-2.5, 0, 0), mass = 0.5, v = vec(1, 0, 0), radius = 0.05, color = color.red, make_trail = True)

obj_2 = sphere(pos = vec(3,0,0), mass = 0.5, v = vec(-0.5, 0, 0), radius = 0.05, color=color.blue, make_trail = True)

obj_1.p = obj_1.mass * obj_1.v
obj_2.p = obj_2.mass * obj_2.v

p_tot = obj_1.p + obj_2.p
E_tot = obj_1.p.mag2/(2 * obj_1.mass) + obj_2.p.mag2/(2 * obj_2.mass)

v_graph = graph(title = 'Velocity', xtitle = 't', ytitle = 'v(t)')
v_obj1_x = gcurve(graph = v_graph, color = color.red)
v_obj2_x = gcurve(graph = v_graph, color = color.blue)

mom_graph = graph(title = 'Momentum', xtitle = 't', ytitle = 'P(t)')
p_obj1_x = gcurve(graph = mom_graph, color = color.red)
p_obj2_x = gcurve(graph = mom_graph, color = color.blue)
p_t_x = gcurve(graph = mom_graph, color = color.purple)

E_graph = graph(title = 'Energy', xtitle = 't', ytitle = 'E(t)')
KE_obj1 = gcurve(graph = E_graph, color = color.red)
KE_obj2 = gcurve(graph = E_graph, color = color.blue)
PE_obj = gcurve(graph = E_graph, color = color.green)
TE_obj = gcurve(graph = E_graph, color = color.purple)

print("P_before: ", p_tot, " E_before: ", E_tot)

myrate = 1000
t = 0
dt = 0.001

scene.waitfor('click')

while obj_2.pos.x < 3.2::
    rate(myrate)
    
    F_1 = vec(0,0,0)
    F_2 = vec(0,0,0)
    
    r = obj_2.pos - obj_1.pos
    PE_spring = 0 
    if r.mag < l_0:
        s = l_0 - r.mag
        F_1 = -k * s * r.hat
        F_2 = k * s * r.hat
        PE_spring = 1/2 * k * s**2
        
    obj_1.p += (F_1*dt)
    obj_1.v = obj_1.p/obj_1.mass
    obj_1.pos += (obj_1.v * dt)
    
    obj_2.p += (F_2*dt)
    obj_2.v = obj_2.p/obj_2.mass
    obj_2.pos += (obj_2.v * dt)
    
    KE1 = 0.5 * obj_1.mass * obj_1.v.mag2
    KE2 = 0.5 * obj_2.mass * obj_2.v.mag2
    TE = KE1 + KE2 + PE_spring
    t += dt
    
    v_obj1_x.plot(pos=(t,obj_1.v.x))
    v_obj2_x.plot(pos=(t,obj_2.v.x))
    
    p_obj1_x.plot(pos=(t,obj_1.p.x))
    p_obj2_x.plot(pos=(t,obj_2.p.x))
    p_t_x.plot(pos=(t,obj_1.p.x + obj_2.p.x))
    
    KE_obj1.plot(pos=(t,KE1))
    KE_obj2.plot(pos=(t,KE2))
    PE_obj.plot(pos=(t,PE_spring))
    TE_obj.plot(pos=(t,TE))
    
p_after = obj_1.p + obj_2.p
E_after = obj_1.p.mag2/(2*obj_1.mass) + obj_2.p.mag2/(2*obj_2.mass)

print('momentum after: ', p_after, ' energy after: ', E_after)
    
Leave a Comment