Luke
Luke

Reputation: 31

Find maximum value from while loop

I'm fairly new to python, and trying to find the max value from a while loop, I've tried making a list but that doesn't seem to work, here is my code, any help appreciated!

The idea of it is to fire a projectile at a user entered velocity at a user defined angle, using equations of motion, the vertical and horiziontal distances are then calculated and plotted. So far the plots show accurate results however when I try to find the maximum height, it just gives me the last value of the while loop. I've tried making a list and finding the max value from that but it gives me only the last value again.

import matplotlib.pyplot as plt 
import math

print("This programme finds the maximum distance that a projectile travels when fired from ground level at an initial velocity.")

print("")

print("Air resistance is negligible")
u= float(input("Please enter the initial velocity: "))

#print(u)

a = -9.81 
xv=0.0
xh=0.0
t=1.0
ang= float(input("Please enter the angle of fire, between 0 and 90 degrees: "))

rad=((math.pi)/(180))*(ang)
uh=(u)*(math.cos(rad)) 
uv=(u)*(math.sin(rad))
print(rad, uh, uv)
while range (xv>=0):

    list=[]
    xv = ((uv)*(t))+((0.5)*(a)*(t)*(t))

    xh = (uh)*(t)
    vv=uv+(a*t)
    vh=uh

    t=t+1
    xv = max(xv)

    plt.plot(xh,xv)
    plt.scatter(xh, xv)
    if xv<=0:
        break

print(list)

print("")
print("The maximum height is", max(xv) , "m, with a flight time of", t, "s")
print("")
print("The velocity when the projectile lands is",vv,"m/s" )


plt.xlabel('Horizontal distance (m)') 

plt.ylabel('Vertical distance (m)') 
plt.show()

Upvotes: 0

Views: 228

Answers (2)

Joffan
Joffan

Reputation: 1480

Don't use keywords as variable names - here, list

You can initialize the list of heights before the while loop starts:

heights = []

then append values as you go through the loop (there are other ways to do this but using your structure...)

    heights.append(xv)

and after the loop finishes you can examine using max

print( max(heights))

Putting that together, the middle of your program might look like:

print(rad, uh, uv)
heights = []
t = 0.0
while xv >= 0:
    # plot this point
    plt.plot(xh,xv)
    plt.scatter(xh, xv)
    # save height
    heights.append(xv)

    # calculate next point
    t += 0.1
    xv = uv*t + 0.5*a*t*t
    xh = uh*t
    vv = uv + a*t
    vh = uh

# xv has gone negative so loop has finished
print (max(heights))

(I reordered, improved the loop to exit properly and reduced the time increment)

Upvotes: 1

SIREN
SIREN

Reputation: 181

You may prepend while loop with

max_xv = 0

Put following line inside the loop

max_xv = max(max_xv, xv)

Then use max_xv as a maximum value

Upvotes: 1

Related Questions