У меня есть симуляция распространения вируса для школьного проекта. Наконец, сама симуляция работает так, как должна (какой бы уродливой и взломанной она ни была, поскольку я новичок в Python).
Я прокручиваю симуляцию n-го числа раз, так что Я могу прийти к статистически значимому конечному результату. Я пытался написать код для экспорта окончательного ответа (количества дней, в течение которого продлится пандемия) для каждой симуляции в матрицу, чтобы я мог экспортировать его, поиграть с ним в Excel и т. д. и выполнить некоторую визуализацию. После каждого моделирования есть значение «дни», которое я пытаюсь сохранить в матрице, поскольку это мой конечный результат.
Однако я могу получить его только для сохранения результата окончательный запуск моделирования и не удается заставить его добавить результат каждого предшествующего моделирования. Желаемый результат – это матрица, длина которой равна количеству выполненных симуляций (n), и имеет конечное значение «дней» для каждого из этих элементов.
Я думаю, проблема с самый внешний цикл, все в ядре работает как надо.
Любая помощь приветствуется!
import numpy #go numpy, you can do it!#
# How many times to run the simulation #
n = s = 3
pandemiclength1 = []
pandemiclength2 = []
while n > 0:
#variable defintions
day = 0
p =0.01
infected = 0
daysinfected = numpy.zeros(60)
z = 0
n = n -1
# Day one of the simulation
print(' ')
print('==========================')
print("DAY: 0")
print('==========================')
result = numpy.random.binomial(1, p, 60)
print (result)
for ele in result:
if (ele == 1):
infected = infected +1
print ("Number Infected:", infected)
#for ele in result:
daysinfected = numpy.where(result == 1, +3, 0) # sets new array to track number of addittional (excl. day 0) days infectious
print("Days Infected")
print(daysinfected)
# ********** Day n of simulation ********** #
# This portion of the code will iterate the daily trials until the number of infected children = 0
while infected > 0: # temporary 0, [x - 1 for x in daysinfected], 0) # for each day, adjust the days infectious for each element
for i in range (len(daysinfected)): #trying to set -1 as imunity
if result == 1 and daysinfected == 0:
result= -1 #asign -1 to value if conditions met
infected = infected - z #you don't want to do this every time...just once...oterhwise you will be constantly be subtracting more and more -1s...broke down betwen day 3 and 4
print("Children Infected at Start of Day:", infected)
#print("debug")
#print(infected)
for i in range(infected): # iterate for the number of initially infected kids
print("---trial", i, "---")
new_values = numpy.random.binomial(1, p, 60) # not 100% why this works or why it is needed for next step - stack exchange help.
result = numpy.where(result == 0, new_values, result*1) # if original result is 1 leave as 1, if 0 replace with new value (could be 0 or 1)
infected = 0 # reset infected counter to 0
for ele in result: # count the number of infected children after each trial
if (ele == 1):
infected = infected +1
for i in range (len(daysinfected)): # set infectious days to two subsequent days if new positve (1) result
if result == 1 and daysinfected == 0: # only set for NEW results not if existing infectious
daysinfected= 3
print(result) # print the resulting matrix after each trial
print("Number Infected:", infected) # print the number of infected children after each trial
print("Days Infected")
print(daysinfected)
z = numpy.count_nonzero(daysinfected == 1) # count number about to be immunized to subtract from start of next day
print("Totalabouttoflip", z)
print("Total Infected at End of", day, "days is", infected)
print("Days Infected - less 1")
print(daysinfected)
pandemiclength2 = numpy.append(pandemiclength1, day)
pandemiclength1 = pandemiclength2
print("The Results of", s+1, "simulations is", pandemiclength2)
Подробнее здесь: https://stackoverflow.com/questions/791 ... atrix-in-n
Сложность помещения конечного результата каждого запуска моделирования в матрицу в numpy. Добавляем только последнюю сим ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как умножить матрицу 2x3x3x3 на матрицу 2x3, чтобы получить матрицу 2x3
Anonymous » » в форуме Python - 0 Ответы
- 65 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как умножить матрицу 2x3x3x3 на матрицу 2x3, чтобы получить матрицу 2x3
Anonymous » » в форуме Python - 0 Ответы
- 58 Просмотры
-
Последнее сообщение Anonymous
-