我开始学习Python,并目睹了一个奇怪的问题,无法在网上找到相关信息。
由于我无法发布实际代码,因此我将使用伪代码。
def model(x):
A = list of length 4
B = list of length 4
C = list of length 4
D = list of length 4
# below methods of calculating X, one of which works
# Method 1: WORKS
X0 = A[0] + B[0] + C[0] + D[0]
X1 = A[1] + B[1] + C[1] + D[1]
X2 = A[2] + B[2] + C[2] + D[2]
X3 = A[3] + B[3] + C[3] + D[3]
X = [X0, X1, X2, X3]
# Method 2: DOES NOT WORK,
X = [A[i] + B[i] + C[i] + D[i] for i in range(4)]
M = list of shape 4x4
result = numpy.matmul(M, X)
# result = [nan, nan, nan, nan] after some iterations
return result
上面的模型返回一个dy/dt
矩阵,我在下面的代码中使用该矩阵进行集成
h = 0.1; # timestep
sim_time = np.arange(0, 1500, h) # timeseries
data = []
for i in sim_time:
xdot = model(x);
x = [a + h * b for a,b in zip(x, xdot)]
data.append(x)
我不明白自己在做什么错。我确实发现这可能是由于浮点错误引起的,但是不确定是否是这种情况或如何解决。
非常感谢您的帮助。
这是在变为nan之前经过一些迭代的结果
[-0.0383724 0.32659622 -0.02615451 0.01465148]
[-0.04153605 0.43814228 -0.02797397 -0.19174319]
[-0.04523129 0.07295898 -0.02615787 0.48396945]
[-0.0502085 0.88057674 -0.03373012 -0.90358412]
[-0.07082689 -0.20715555 0.00221235 1.75009264]
[-0.06635629 1.67610358 -0.04464798 -2.09508071]
[-0.0996444 -0.47602223 0.01246201 2.41644675]
[ -32.63095619 564.81941652 -14.72529351 -1025.05888268]
[-4.51778757e+09 -8.04785367e+10 2.09936804e+09 1.42336386e+11]
[-1.54489920e+31 2.75142984e+32 -7.17739692e+30 -4.86623834e+32]
[-3.08719207e+90 -5.49821772e+91 1.43426848e+90 9.72426681e+91]
C:\Users\Mod_18122018.py:323: RuntimeWarning: overflow encountered in double_scalars
state_derivative =[X[0]*(U**2/L), X[1]*(U**2/L), X[2]*(U**2/L**2), X[3]*(U**2/L**2)]
C:\Users\Mod_18122018.py:205: RuntimeWarning: invalid value encountered in double_scalars
u =x[4]/U
C:\Users\Mod_18122018.py:206: RuntimeWarning: invalid value encountered in double_scalars
v =x[5]/U
C:\Users\Mod_18122018.py:207: RuntimeWarning: invalid value encountered in double_scalars
p =x[7]*L/U
C:\Users\Mod_18122018.py:208: RuntimeWarning: invalid value encountered in double_scalars
r =x[6]*L/U
C:\Users\Mod_18122018.py:233: RuntimeWarning: invalid value encountered in double_scalars
u = (x[4] - uc)/U;
C:\Users\Mod_18122018.py:234: RuntimeWarning: invalid value encountered in double_scalars
v = (x[5] - vc)/U;
C:\Users\Mod_18122018.py:265: RuntimeWarning: invalid value encountered in double_scalars
n_c=n_c*U/L;
C:\Users\Mod_18122018.py:266: RuntimeWarning: invalid value encountered in double_scalars
n=n*U/L;
[nan nan nan nan]
[nan nan nan nan]
[nan nan nan nan]
[nan nan nan nan]
[nan nan nan nan]
[nan nan nan nan]