python - IndexError:列表索引超出范围的原因是什么?
问题描述
所以,我的教授让我创建一个程序,使用 Runge-Kutta 方法(二阶)来解决这个问题。但是我得到一个 IndexError: list index out of range ,这可以追溯到我的第一个函数。我不完全理解这里的错误是什么,如果有人向我解释它会很高兴
import numpy as np
def f(a, rec, inf, j, b, q):
f = b*(1-inf[j]-rec[j])*(a[j][0]*inf[0]+a[j][1]*inf[1]+a[j][2]*inf[2]+a[j][3]*inf[3]+a[j][4]*inf[4]+a[j][5]*inf[5]+a[j][6]*inf[6]+a[j][7]*inf[7]+a[j][8]*inf[8]+a[j][9]*inf[9]) - q*inf[j]
return f
def rk2a(I, R, b, q):
beta = b
sigma = q
I.astype(float)
R.astype(float)
n = len(I)
S = 1 - I - R
A = np.array([[0,1,1,1,0,0,0,0,0,0],
[1,0,1,1,1,0,0,0,0,0],
[1,1,0,1,1,1,0,0,0,0],
[1,1,1,0,1,1,1,0,0,0],
[0,1,1,1,0,1,1,1,0,0],
[0,0,1,1,1,0,1,1,1,0],
[0,0,0,1,1,1,0,1,1,1],
[0,0,0,0,1,1,1,0,1,0],
[0,0,0,0,0,1,1,1,0,1],
[0,0,0,0,0,0,1,0,1,0]])
y_coef = []
old_I = []
for i in range(0,50,1):
print(I.transpose())
for j in range(0,n-1,1):
k1 = f(A,R,I,j,beta,sigma)
y_coef.append(I[j])
old_I.append(I[j])
y_coef[j] = I[j]+(k1/2)
k2 = f(A, R, y_coef, j, beta, sigma)
I[j] = old_I[j] + k2
return None
infect = np.array([0, 1, 0, 0, 0, 0, 0, 1, 0, 0])
recov = np.array([0,0, 0, 0, 0, 0, 0, 0, 0, 0])
rk2a(infect, recov, 0.3, 0.1)
解决方案
Leave the indices out totally. All numpy array arithmetic operations are cell-by-cell. The linear-algebraic matrix-vector product is numpy.dot
or the .dot
method of arrays. So you could rewrite
def f(inf, rec, A,b,q)
susc = 1-inf-rec # computes the susceptibles in every node
trans = b*susc*A.dot(inf) # newly infected in time span
recov = q*inf # recovered in time span
return trans-recov, recov
and then iterate
for t in time[:-1]:
k1i, k1r = f(inf,rec,A,b,q)
k2i, k2r = f(inf+k1i*dt/2,rec+k1r*dt/2,A,b,q)
inf, rec = inf + k2i*dt, rec+k2r*dt
I.append(inf); R.append(rec);
推荐阅读
- python - 如何从多个 DataFrame 更新 pandas DataFrame 的计数列?
- java - Hibernate - 如何急切地加载惰性字段?
- r - 当两个特定列总和为零时删除数据帧行
- python - 使用 selenium 和 BeautifulSoap 进行网页抓取
- javascript - 在javascript中以以下形式将javascript嵌套的对象数组与父对象合并?
- github - Azure Devops 无法根据 Github 标签创建发布触发器
- go - 使用 Go reflect 实例化一个新的 obj 并在接口中输入 assert
- virtual-machine - 如何使用 pwndbg 显示块信息
- c# - .NET Core 的 Application Insights 仅显示比“警告”更差的调试级别
- c# - 此 SqlParameterCollection 不包含具有 ParameterName 'server_name' 的 SqlParameter