迭代解python(找到最后和最后一个迭代值)

时间:2015-06-18 18:54:22

标签: python iteration

我是编程的初学者,必须在python中编写一个简短的代码。它是关于在连续迭代之间的差异不超过0.0001时找到变量的迭代解决方案。

我想过使用无限循环但是如何检查在倒数第二次和最后一次迭代后获得的值是什么,以便我可以指定中断条件。

请有人解释一下如何做到这一点吗?

以下是我编写的代码

Icl=0.5
tc= 25 
def kelvin(tc):
    tk = tc +273.15
    return tk

#calculate the initial value for tcl

tcl=kelvin(tc)+(35.5-tc)/(3.5*Icl+0.1)

#calculate the final value of tcl when the difference between the successive values of tcl <0.0001

while true:
    tcl=35.7-0.028*(M-Icl)*(3.96e-8*fcl((tcl+273.15)**4-(tr+273.15)**4+fcl*hc*(tcl-ta))

    if .... #here I am not sure how to break the loop when above mentioned condition is met

1 个答案:

答案 0 :(得分:0)

在您的代码中,您只需将tcl存储在需要存储tclprevious_tcl的位置。至少,您可以通过以下方式修改代码:

cl=0.5 tc= 25 def kelvin(tc): tk = tc +273.15 return tk

#calculate the initial values for tcl and tcl_previous
tcl_previous = kelvin(tc)+(35.5-tc)/(3.5*Icl+0.1)
tcl = 35.7-0.028*(M-Icl)*(3.96e-8*fcl((tcl_previous+273.15)**4-(tr+273.15)**4+fclhc(tcl_previous-ta))

#calculate the final value of tcl when the difference between the successive values of tcl <0.0001

while math.abs(tcl-tcl_previous)>0.0001:
    tcl_previous = tcl
    tcl = 35.7-0.028*(M-Icl)*(3.96e-8*fcl((tcl_previous +273.15)**4-(tr+273.15)**4+fclhc(tcl_previous -ta))

请注意,这不是更清晰的编写方式,因为从tcl计算tcl_previous的行是重复的。你应该把它封装在一个函数中。