[英]Python for loop not iterating for i=1,2 only outputting first iteration
I am building a for loop using Euler's method for differential equations. 我正在使用欧拉微分方程方法构建for循环。 The for loop however is not incrementing and only displaying the values for i=0 and not i=1 or i=2.
但是,for循环不会递增,仅显示i = 0的值,而不显示i = 1或i = 2的值。
I have tried manually assigning all arguments and reconstructed the for loop. 我尝试过手动分配所有参数,并重建了for循环。
import math
def Euler(a,b,N,alpha):
h=(b-a)/N
t=a
w=alpha
for i in range (0,N):
w=w+h*(math.exp(t-w))
t=a+(i*h)
return t,w
Euler(0,1,2,1)
I expect the function to return results for i=1 and i=2 我期望函数返回i = 1和i = 2的结果
As pault mentioned in the comments, your return is inside the loop, which means the function exits on the first iteration. 正如评论中提到的pault一样,您的返回位于循环内部,这意味着该函数在第一次迭代时退出。
What you probably want is yield
, which would turn the function into a generator: 您可能想要的是
yield
,它将功能转换为生成器:
import math
def Euler(a,b,N,alpha):
h=(b-a)/N
t=a
w=alpha
for i in range (0,N):
w=w+h*(math.exp(t-w))
t=a+(i*h)
yield t,w
for x, y in Euler(0,1,2,1):
print(x, y)
>>> 0.0 1.1839397205857212
>>> 0.5 1.3369749844848988
Your return is in the for
loop. 您的回报在
for
循环中。 Unindent return
once. 一次缩进
return
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.