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

2024-05-14 06:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的代码的最后一部分,我需要输出最大速度和速度最大的角度,但是我们不允许使用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]))

用我的代码,我返回所有的角度值和速度,我不知道如何输出只是最大速度与相应的角度

谢谢你的帮助


Tags: 代码plotnppositioncmpltsin速度
2条回答

最简单的方法是获取最大值的索引(尽管通常我会选择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,与图表相比似乎相当准确

将所有velocity/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)

相关问题 更多 >