简体   繁体   中英

Basic Python bouncing ball question (and possibly nested loop?)

What I am trying to achieve here is to create a trajectory of a ball falling and bouncing back, the equation of that motion is y, and every time the ball bounces back, the v_0 become e*v_0, or 3/4 of before. I started by calculating the y(t) without bouncing, letting y go negative, then the negative part of the trajectory would be replaced by a new trajectory that starts with a bounce, and its v_0 would be 3/4 of before, then repeat until there are no negative y values left. (I tried a nested loop but I haven't really figured out how, we don't have to use a nested loop but I don't really see another way). Eventually, I want to produce an array with all the y of the ball using the t_test below the function.


def traj_y_bounce(t, v_0, y_0=0, e=0.75):    
    y = y_0 + v_0 * t - (1/2)*g*(t**2)
    return y
#    for i in range(len(y)):
#        while y[i] < 0:
#            y[i] == 
#    return y



#t_test = np.linspace(0,5,10)
#print(traj_y_bounce(t_test, 4))

Here's a simple simulation example of a ball dropped from height h

def traj_y_bounce(tmax, v0, y0, e0=0.75):
    g = 9.9 # meters/s/s
    y = [y0] # heights over time

    dt = 0.01 # integrate in hundredths of a second

    v = v0
    t = 0
    while t <= tmax:
        if y[-1] <= 0 and v < 0:
            v = -e0*v   # reflect off ground
        v = v - g*dt    # integrate velocity
        y.append(y[-1] + v*dt)  # integrate position

        t = t + dt  # integrate time
    return y

y = traj_y_bounce(5, 0, 10)

%matplotlib notebook
import matplotlib.pyplot as plt
plt.plot(y, linewidth=4, label='height')
plot.show()

Plot 模拟

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM