[英]TypeError in Python Euler's Method Simulation
我正在嘗試在Python中為簡單的SIR類型模型模擬Euler方法。 為此,我正在執行以下操作:
當我這樣做時,我收到如下的TypeError:
TypeError: unsupported operand type(s) for -: 'float' and 'list'
我嘗試了打印語句調試,以確保我對該函數(在本例中為s_next函數)的輸入都是int和float(它們是),但是我仍然收到此錯誤。 我的代碼如下。
import numpy as np
#Parameters
mu = 0.56
epsilon = 0.01 #* time_step
z = 0.05 * 0.21 #(percent with aids * aids death rate)
p = 0.25 #* time_step
q = 0.05 #* time_step #Assumption
beta = 0.01
#dS Function
def s_next(S, P, I, time_step):
return S + time_step * ((S * epsilon) + (q * P) - (p * S) - (beta * S *
I))
#dP Function
def p_next(S, P, I, time_step):
return P + time_step * ((p * S) - (q * P) - (mu * (beta * P * I)))
#dI Function
def i_next(S, P, I, time_step):
return I + time_step * ((beta * S * I) + (mu * beta * P * I) - (z * I))
#Arrays For Each Compartment
time_values = np.arange(0, 100, 0.1)
s = [0] * len(time_values)
p = [0] * len(time_values)
i = [0] * len(time_values)
s[0] = 56400
p[0] = 1000
i[0] = 10575
#For Loop For Array Iteration
for increment in range(1, len(time_values)):
s_current_value = int(s[increment - 1])
p_current_value = int(p[increment - 1])
i_current_value = int(i[increment - 1])
print('s_current_type', type(s_current_value))
print('p_current_type', type(p_current_value))
print('i_current_type', type(i_current_value))
s_next_value = s_next(s_current_value, p_current_value, i_current_value,
0.1)
p_next_value = p_next(s_current_value, p_current_value, i_current_value,
0.1)
i_next_value = i_next(s_current_value, p_current_value, i_current_value,
0.1)
s[increment] = s_next_value
p[increment] = p_next_value
i[increment] = i_next_value
您已經兩次使用了變量名p
。 一次,在代碼的頂部,然后在初始化列表時再次:
p = 0.25 #* time_step
#.....
p = [0] * len(time_values)
因此,在您的s_next
函數中,嘗試執行(p * S)
,它認為p
是您的列表,而不是值0.25(可能是您想要的值)。
解決方案是重命名列表或變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.