【发布时间】:2021-07-29 05:33:39
【问题描述】:
我正在将此 matlab 代码转换为 Python,但显然我犯了一个小错误,即结果不一样。这是matlab代码:
alpha = 0.1;
beta = 0.01;
Dt = 0.001;
N = 1000;
time = 0:Dt:40;
state = zeros(length(time),N);
R = rand(length(time)-1,N);
for j = 1:N
for i = 2:length(time)
if (state(i-1,j) == 0)
if (R(i-1,j) <= alpha*Dt)
state(i,j) = 1;
else
state(i,j) = 0;
end;
else
if (R(i-1,j) <= beta*Dt)
state(i,j) = 0;
else
state(i,j) = 1;
end;
end;
end;
end;
Open_stochastic = sum(state,2)/N;
open_deterministic = (1-exp(-time*(alpha+beta)))*alpha/(alpha+beta);
plot(time, Open_stochastic, ’k-’, time, Open_deterministic, ’k--’)
这是我的python代码:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
alpha = 0.1
beta = 0.01
Dt = 0.001
N = 1000
time = np.arange(0, 40, Dt)
state = np.zeros((len(time), N))
R = np.random.rand(len(time), N)
for j in range(0, N-1):
for i in range(1, len(time)-1):
if state[i-1][j] == 0:
if R[i-1][j] <= alpha*Dt:
state[i][j] = 1
else:
state[i][j] = 0
if R[i-1][j] <= beta*Dt:
state[i][j] = 0
else:
state[i][j] = 1
open_stochastic = state.sum(1)/N
plt.plot(time, open_stochastic)
【问题讨论】:
-
声明
state[i][j] == 1什么都不做。那里的等号太多了。 -
@TimRoberts 感谢您的 cmets,并为我的草率错误感到抱歉。我更正了我的原始代码,但结果仍然不一样,请看图片
-
你应该更正那些智能引号
-
@MadPhysicist 你能指定“智能引号”吗?
-
例如
’k-’->'k-'
标签: python matlab for-loop if-statement