超越方程

时间:2014-08-12 12:11:59

标签: python equation

我面临着解决先验方程式的任务:

K = K0*(exp(-t*B)/1+L*B)

变量'B'未知。我必须为B的第一步采用下一个表达式:

B = (K0-1)/(L+t)

对于第二步和所有后续步骤,我必须将B计算为:

B = -(1/t)*ln((1+L*B)/K0)

当B的前一个值和当前值之间的相对差异不超过1%时,迭代停止。得到的B应该使第一个等式右边的部分等于1。 我怎么能用python做到这一点?我听说过来自scipy的零查找例程,但我真的更喜欢一些普通的编码(它会帮助我更好地理解事物)。我试过了while循环。当第一个等式中的K足够接近1.0时,我可以写一个循环来迭代并停止迭代:

kinf = 1.123456e+00

tau = 2.832995e+01

L2 = 3.745903e+00

i = 1

b2 = (kinf-1)/(L2+tau)

def iterate():
    b = b2
    i = 1
    print "iteration no.{:.1f}; B^2 = {:.06e}; delta = {:.03f}".format(i, b, kinf*((exp(-tau*b))/(1+L2*b)) - 1.0)
    while abs(kinf*((exp(-tau*b))/(1+L2*b))-1.0)>0.0001:
        b = -(1/tau)*log((1+L2*b)/kinf)
        i+=1
        print "iteration no.{:.1f}; B^2 = {:.06e}; delta = {:.03f}".format(i, b, kinf*((exp(-tau*b))/(1+L2*b)) - 1.0)

但是我无法理解,我如何比较B的先前和当前值。我想,这个问题是经典问题之一,但我感谢任何帮助。

UPD: 谢谢您的帮助! 我现在正在做吗?

def iterate():
b0 = (kinf-1)/(L2+tau)
bold = b0
b = -(1/tau)*log((1+L2*b0)/kinf)
bnew = b
diff = ((bnew-bold)/bnew)*100
while abs(diff)>=0.01:
    print 'previous B^2 = {:.06e}'.format(bold)
    bnew = -(1/tau)*log((1+L2*bold)/kinf)
    print 'B^2 = {:.06e}'.format(bnew)
    diff = ((bnew-bold)/bnew)*100
    print 'delta = {:.06e}'.format(diff)
    bold = bnew

2 个答案:

答案 0 :(得分:0)

要在迭代过程中完成此操作,您可以创建一个previous_b变量并将其初始化为None。然后在while循环中,如果previous_b为None 差异大于阈值,则继续。

kinf = 1.123456e+00

tau = 2.832995e+01

L2 = 3.745903e+00

i = 1

b2 = (kinf-1)/(L2+tau)

def iterate():
    previous_b = None
    b = b2
    i = 1
    print "iteration no.{:.1f}; B^2 = {:.06e}; delta = {:.03f}".format(i, b, kinf*((exp(-tau*b))/(1+L2*b)) - 1.0)
    while previous_b is None or abs(kinf*((exp(-tau*b))/(1+L2*b))-1.0)>0.0001:
        previous_b = b
        b = -(1/tau)*log((1+L2*b)/kinf)
        i+=1
        print "iteration no.{:.1f}; B^2 = {:.06e}; delta = {:.03f}".format(i, b, kinf*((exp(-tau*b))/(1+L2*b)) - 1.0)

答案 1 :(得分:0)

请勿覆盖此行中的b(您将以这种方式忽略b的旧值):

b = -(1/tau)*log((1+L2*b)/kinf) # the old value of b gets lost here

相反,您可以在while循环中执行此操作:

b_new = -(1/tau)*log((1+L2*b)/kinf)
b_delta = b_new - b
# do whatever you want with b_delta and finally override the old b with the new b
b = b_new