将结果添加到列表并设置 for 循环

Adding Results to a List and Setting up a for-loop

对于一项学校作业,我正在编写一个使用欧拉法计算斜率的算法。在其中的一部分,我有一个 for 循环,它将重复方程式的模式,直到满足最终结果。我需要的是一种将每个结果添加到列表中然后绘制列表中每个项目的方法。如果可能的话,我还需要一些帮助来设置 for 循环。

这就是我所拥有的,记住我在编码方面非常缺乏经验(请耐心等待)

stpsz = input ("Define "h" Value (step size)")
tfinal = input ("Define Final "T" Value (stopping place)")
xnow = input ("Define "X0" as a Starting Value")

t = 0
while t > tfinal
    t = t + 1
    slopenow = (xnow * (1-xnow))

#Save slopenow (as a number, not variable) to a list of slopes ( I don't understand how to make a list like this)
#Save xnow (as a number, not variable) to a list of xs)

    xnext = (slopenow * stpsz)+(xnow)
    xnext = x now

#repeat while-loop until tfinal is reached)

我非常感谢你们能提供的任何帮助。

听起来您正在寻找的是 while 循环。像这样:

t = 0
while t < 10:
    t = t + 1
    # more code here

这里有 this 方程的递归方法,让您了解我在评论中的意思。

class Slope:
    def __init__(self, timestamp, slope):
        self.timestamp = timestamp
        self.slope = slope


def find_slope(slopes, slope, step_size, until):
    if slope.timestamp > until:
        return slopes
    current_y = slope.slope + step_size * slope.slope
    slope = Slope(slope.timestamp + 1, current_y)
    slopes.append(slope)
    return find_slope(slopes, slope, step_size, until)

if __name__=="__main__":
    initial_slope = Slope(0, 1)
    for current in find_slope([], initial_slope, 1, 3):
        print("slope: {slope}, timestamp: {timestamp}".format(**current.__dict__))

但是有多种方法可以解决这个问题,例如用 while 或 for 循环。我也不得不承认你可以写一个更短的版本,但我认为冗长的内容有助于你更好地理解。

编辑

你的眼睛应该关注那个功能...

def find_slope(slopes, slope, step_size, until):
    if slope.timestamp > until:
        return slopes
    current_y = slope.slope + step_size * slope.slope
    slope = Slope(slope.timestamp + 1, current_y)
    slopes.append(slope)
    return find_slope(slopes, slope, step_size, until)

这是一个 recursive 调用或更简单的函数,只要到达某个点就会调用自身,这里是 if slope.timestamp > until。第一个电话是我的 initial_slopestep_sizeuntil 只是常量)。

current_y = slope.slope + step_size * slope.slope计算新的斜率值。然后我使用新的斜率值和更新的时间创建一个斜率实例并将其添加到列表中。

斜率实例、斜率列表和常量通过函数的自调用传递到下一步return find_slope(slopes, slope, step_size, until)。 return 不仅需要下梯子并收集新的斜坡,而且 return 回到起点以便调用者可以接收它。

你可以用

调用递归函数
 slopes = find_slope([], initial_slope, 1, 3)

并返回一个斜坡列表。我用一个空列表初始化它,该列表将填充斜率,然后 return 从这个函数编辑。