如何从具有对应角度的数组中返回最大的值

时间:2018-10-18 19:19:17

标签: python arrays max

对于我的代码的最后一部分,我需要输出最大速度和最大速度的角度,但是我们不允许使用max函数。到目前为止,我的代码:

#This program calculates and plots the position and velocity of a piston
import numpy as np 
import matplotlib.pyplot as plt

def piston_position(r,l,a):
    #input: r = radius (cm), l = length (cm), a = angle (radians)
    #output: x = position (cm)
    x = (r * np.cos(a) + ((l**2) - (r**2) * (np.sin(a)**2)**0.5))
    return x

def piston_velocity (r, l, a, w):
    #input: r = radius (cm), l = length (cm), a = angle (radians), w = angular velocity (radians/seconds)
    #output: v = velocity (cm/s)
    v = (-r * w * np.sin(a) - ((r**2 * w * np.sin(a) * np.cos(a))/((l**2 - r**2 *np.sin(a)**2)**0.5)))
    return v 

a = np.linspace(0,360,30)
x1 = piston_position(3,15,a)
v1 = piston_velocity(3,15,a,100)
x2 = piston_position(5,15,a)
v2 = piston_velocity(5,15,a,100)

plt.figure(1)
plt.subplot(211)
plt.plot(a,x1, 'b^--', label ='r=3cm', mfc = 'r', color = "black")
plt.plot(a,x2, 'bs--', label ='r=5cm', mfc = 'b', color = "black")
plt.title ("Subplot for Position")
plt.ylabel ("Position (cm)")
#plt.xlabel ("Angle (degrees)") --- Note: caused an overlap in text
plt.legend()

plt.subplot(212)
plt.plot(a,v1, 'b^--', label ='r=3cm', mfc = 'r', color = "black")
plt.plot(a,v2, 'bs--', label ='r=5cm', mfc = 'b', color = "black")
plt.title ("Subplot for Velocity")
plt.ylabel ("Velocity (cm/s)")
plt.xlabel ("Angle (degrees)")
plt.legend()
plt.show() 

a3 = np.array(a)
v3 = sorted(piston_velocity(3,15,a3,100))
v4 = piston_velocity(5,15,a3,100)
for i in range(0,len(v3)):
    print((int(a3[i])),int(v3[i]))

使用代码我可以返回所有角度值和速度,但我不确定如何仅输出最大速度及其对应的角度。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

将所有速度/ agle元组收集到一个列表中。

创建自己的max函数-python是一种编程语言:

def getMax(iterab):
    """Returns the larges number (or > / __ge__(self,a,b) is defined) value) from iterab"""
    c = iterab[0] # make sure it has content
    for other in iterab[1:]:
        if other > c:
            c = other

    return other

def getMaxTuple(tupsIter,idx=0):
    """Returns the tuple from tupsIter with the larges value on position idx"""
    c = tupsIter[0]
    for other in tupsIter[1:]:
        if other[idx] > c[idx]:
            c = other

    return other

打印它们:

print(getMax(range(2,5)))  # 4

print(getMaxTuple( [ (a,a**3) for a in range(10) ],1 ))  # (9,729)

答案 1 :(得分:0)

最简单的方法是获取最大值的索引(尽管通常我会选择np.argmax):

index = 0
value = v1[0]
for i in range(len(v1)):
     if v1[i] > value:
          index = i
          value = v1[i]

然后您可以使用以下方法获取角度:

angle = a[index]

这将返回v1的最大速度:305.9m / s,角度为111.7,与图形相比,这看起来非常准确。