我想把这个vba代码变成python,但我陷入了嵌套循环。这是vba代码和结果
表方程 :
Sub iter_K()
num_HW = 4
For i = 1 To num_HW
For k = 1 To 0.01 Step -0.01
Range(Cells(1 + i, 5), Cells(1 + num_HW, 5)) = k
'Cells(1 + i, 5) = k
status_gap = Cells(1 + i, 10)
If status_gap = 1 Then Exit For
Next k
Next i
End Sub
以下是表中各列的说明:
这是我的 python 代码,但它不会返回与 vba 脚本相同的结果:
def calculate_water_flow(QL, QD, K):
num_HW = len(QL)
n = 1
QA = []
QR = []
QS = []
K_real = []
Gap_K = []
for i in range(0, num_HW):
if i == 0:
qa = QL[i]
else:
qa = QL[i] + (QS[i - 1] if i >= 1 else 0)
QA.append(qa)
qr = min(K * QD[i], qa)
QR.append(qr)
qs = qa - qr
QS.append(qs)
k_real = qr / QD[i]
K_real.append(k_real)
Gap_K = [0] + [K_real[i] - K_real[i - 1] for i in range(1, num_HW)]
return QA, QR, QS, K_real, Gap_K
def print_results(QA, QR, QS, K_real, Gap_K, iterations):
num_HW = len(QA)
print("HW\tQL\tQA\tQD\tK\tQR\tQS\tK_real\tGap_K\tStatus_Gap")
for i in range(num_HW):
status_gap = 1 if Gap_K[i] <= 0.01 else 0
print(f"{i + 1}\t{QL[i]}\t{QA[i]:.2f}\t{QD[i]}\t{K:.2f}\t{QR[i]:.2f}\t{QS[i]:.2f}\t{K_real[i]:.2%}\t{Gap_K[i]:.2%}\t{status_gap}")
print(f"Total iterations: {iterations}")
if __name__ == "__main__":
QL = [50, 30, 80, 60]
QD = [100, 150, 120, 80]
K = 1
iteration = 0
QA, QR, QS, K_real, Gap_K = calculate_water_flow(QL, QD, K)
while any(gap > 0.01 for gap in Gap_K):
iteration += 1
K -= 0.01
if K < 0.01:
K = 0.01
QA, QR, QS, K_real, Gap_K = calculate_water_flow(QL, QD, K)
print_results(QA, QR, QS, K_real, Gap_K, iteration)
我们来比较一下
HW=1
上的交互。
VBA 代码验证 Gap_K <0.01 (formula in J2) for current row (row# is 2).
status_gap = Cells(1 + i, 10)
If status_gap = 1 Then
Exit For
End If
Py 代码尝试验证
Item of Gap_K list<0.01
,Gap_K
列表中有 4 项。
while any(gap > 0.01 for gap in Gap_K)