问题
I'm defining a function for solving my differential equations in scipy's solve_ivp.
def conv(t,Z):
global sw,von,X
if sw==0 and X[1]>=von or sw==1 and X[0]>0:
zdot=LA.inv(v1).dot(A1).dot(v1).dot(Z).reshape(4,1)+LA.inv(v1).dot(B1).dot(U)
sw=1
von=0.7
X=v1.dot(Z)
else:
zdot= LA.inv(v0).dot(A0).dot(v0).dot(Z).reshape(4,1)+LA.inv(v0).dot(B0).dot(U)
sw=0
X=v0.dot(Z)
return np.squeeze(np.asarray(zdot))
and solving my equation using
sw=0
e1,v1=LA.eig(A1)
von=0
Z= np.array([0, 0, 0, 0])
X=v1.dot(Z)
U = np.array([[vin], [vdon]])
Z0= np.array([0, 0, 0, 0])
V=v1
sol = solve_ivp(conv, tspan,Z0,method='Radau')
Initially as sw
=0
and X
=[0,0,0,0]
, I expect the if
condition to be satisfied and the if block
to be implemented. But the program is executing the else block.I'm not able to understand the problem.
回答1:
According to Python Zen N2 "Explicit is better than implicit"
def conv(t,Z):
global sw,von,X
if sw==0 and (X[1]>=von or (sw==1 and X[0]>0)):
zdot=LA.inv(v1).dot(A1).dot(v1).dot(Z).reshape(4,1)+LA.inv(v1).dot(B1).dot(U)
sw=1
von=0.7
X=v1.dot(Z)
else:
zdot= LA.inv(v0).dot(A0).dot(v0).dot(Z).reshape(4,1)+LA.inv(v0).dot(B0).dot(U)
sw=0
X=v0.dot(Z)
return np.squeeze(np.asarray(zdot))
Then debugger is the best way to find why you have True or (False and (False)) I may see from the values you have already provided that
(sw==1 and X[0]>0)
is equal to False becauseX[0]=0
in your initial conditionYou have not mentioned what is the value of
von
in the(X[1]>=von)
But based on results you get von
is greater than 0. Check that and make explicit comparisons in the code. This will help a lot in the future.
来源:https://stackoverflow.com/questions/61498295/if-else-condition-not-working-as-expected-in-pythons-scipy-code