[英]Numpy arrays incorrectly have identical values?
我有一個小程序,我正在玩創建與疾病傳播相關的進化算法。 我遇到了一個問題,讓我有點瘋狂地試圖找出問題所在。
我有兩個 numpy arrays,“感染”,這是一個數組,其中每個元素都是該個人是否已暴露的二進制表示和“current_infections”,這只是持續感染,應該按天遞增。
例如:
感染 = [0,0,0,1,1]
current_infections = [0,0,0,15,0]
這將代表 5 個人,其中 3 個人患有該病 15 天,而 4 個人患有該病的時間足夠長,以至於他們已經康復並且目前不再患有該病。
infections = []
current_infections = []
responsible_infections = []
spread_rate = 0.1
contagious_period = 20
initial_node_infections = 2
current_network = #this is an array of adjacency matrices for nodes in a network
#initial infections.
def initialize_infections():
global infections, current_infections, responsible_infections
responsible_infections = np.zeros(current_network.shape[0])
infections = np.zeros(current_network.shape[0])
for each in rd.sample(range(len(current_network)), k=initial_node_infections):
infections[each] = 1
current_infections = infections[:]
# runs a day in simulation.
# returns 1 if there are still ongoing infections at the end of day, 0 if not
def progress_day():
global current_infections
print(np.sum(current_infections), np.sum(infections)) #should not be equivalent, yet they are
for i in range(len(current_infections)):
if current_infections[i] >= 1 and current_infections[i]<contagious_period:
current_infections[i]+=1
elif current_infections[i]>=contagious_period:
#patient recovered
current_infections[i] = 0
for i in range(contacts_per_day):
for j in range(len(current_infections)):
if current_infections[j] >= 1:
spread_infection(current_network[j], j)
if not np.sum(current_infections):
return 0
else:
return 1
#given infected node it calculates spread of disease to adjacent nodes.
def spread_infection(person, rp):
global infections, current_infections, responsible_infections
for x in range(len(person)):
if person[x] == 1 and infections[x] == 0 and rd.random()<=spread_rate:
current_infections[x] = 1
infections[x] = 1
responsible_infections[rp]+=1 #infections a given person is responsible for.
def main():
global current_infections, infections
initialize_infections()
day = 0
while day<100:
if not progress_day():
break
day+=1
main()
出於某種原因,對 current_infections 中的元素所做的更改也在感染中對該元素進行了更改,因此它們都在遞增。 我是否對 numpy 做錯了什么,以至於它們在某種程度上是同一個數組?
current_infections = infections[:]
使 current_infections 成為感染元素的視圖。 使用current_infections = infections.copy()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.