<p>这里有一个<a href="https://en.wikipedia.org/wiki/Euler_method" rel="nofollow noreferrer">this</a>方程的递归方法,让您了解我在评论中的意思。你知道吗</p>
<pre><code>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__))
</code></pre>
<p>但是有多种方法可以解决这个问题,例如使用while或for循环。我也不得不承认你可以写一个简短的版本,但我认为冗长有助于你更好地理解。你知道吗</p>
<p><strong>编辑</p>
<p>你的眼睛应该集中在这个功能上。。。你知道吗</p>
<pre><code>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)
</code></pre>
<p>这是一个<a href="https://www.python-course.eu/recursive_functions.php" rel="nofollow noreferrer">recursive</a>调用或更简单的函数,只要到达某个点,它就会调用自身。第一个调用是my<code>initial_slope</code>(<code>step_size</code>和<code>until</code>只是常量)。你知道吗</p>
<p>行<code>current_y = slope.slope + step_size * slope.slope</code>计算新的斜率值。然后用新的slope值和更新的时间创建一个slope实例,并将其添加到列表中。你知道吗</p>
<p>slope实例、slope列表和常量通过函数<code>return find_slope(slopes, slope, step_size, until)</code>的自调用传递到下一步。返回不仅需要走下阶梯,收集新的斜坡,而且还需要返回到起点,以便调用者能够接收到它。你知道吗</p>
<p>您可以使用</p>
<pre><code> slopes = find_slope([], initial_slope, 1, 3)
</code></pre>
<p>把斜坡的清单拿回来。我用一个空列表初始化了它,该列表将填充坡度,稍后将从此函数返回。你知道吗</p>