问题
I've faced a task to solve a transcendental equation:
K = K0*(exp(-t*B)/1+L*B)
Variable 'B' is unknown. I have to take the next expression for B for a first step:
B = (K0-1)/(L+t)
For the second step and for all the next steps I have to calculate B as:
B = -(1/t)*ln((1+L*B)/K0)
The iteration stops when relative difference between the previous and the current value for B doesn't exceed, say, 1%. The resulting B should make the first equation right part be equal to 1. How can I do it with python? I've heard about zero-finding routines from scipy, but I really would prefer some ordinary coding (It would help me to understand things better). I've tried the while loop. I can write a loop to iterate and stop iterating when K from the first equation is close enough to 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)
But I can't understand, how do I compare previous and current values of B. I suppose, this problem is one of classic ones, but I appreciate any help.
UPD: Thank you for your help! Am I doing it right now?
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
回答1:
Don't override b
in this line (you'll loose the old value of b
this way):
b = -(1/tau)*log((1+L2*b)/kinf) # the old value of b gets lost here
Instead you can do this within your while
-loop:
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
回答2:
To accomplish this while iteration you can create a previous_b
variable and initialize it to None
. Then in your while loop, continue if previous_b is None or difference is greater than your threshold.
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)
来源:https://stackoverflow.com/questions/25263965/transcendental-equation