目前将范围值打印到终端。我需要将这些值导出到csv文件。 "打印S [t-1],I [t-1],R [t-1]"是值......
import matplotlib.pyplot as plt
import numpy
beta = 0.24
gamma = 0.142857
Tstart = 0
Tend = 151
r = 0
s = (306.8 * 10**6)
i = (22 * 10**6)
def compute_next_day(t,R,I,S):
R[t] = gamma * I[t - 1] + R[t - 1]
I[t] = (beta * I[t-1] * S[t-1] / (r+i+s)) - gamma * I[t-1] + I[t-1]
S[t] = - (beta * I[t-1] * S[t-1] / (r+i+s)) + S[t-1]
print S[t-1], I[t-1], R[t-1]
def compute_entire_period(Tstart, Tend, R, I, S):
R[Tstart] = r
I[Tstart] = i
S[Tstart] = s
for t in range(Tstart + 1, Tend):
compute_next_day(t, R, I, S)
R = range(Tstart, Tend)
I = range(Tstart, Tend)
S = range(Tstart, Tend)
答案 0 :(得分:0)
这样的事情应该有效:
def compute_next_day(t,R,I,S,):
...
return S[t-1], I[t-1], R[t-1] # return values instead of printing to terminal
with open('path_to_file.csv','w') as f:
for ... : # your choice of loop
vals = compute_next_day(...) # compute your values
f.write(','.join(vals) + '\n') # dump your values separated with ','
答案 1 :(得分:0)
如果要以CSV格式保存数据,请使用dsv库:
import csv
beta = 0.24
gamma = 0.142857
Tstart = 0
Tend = 151
r = 0
s = (306.8 * 10 ** 6)
i = (22 * 10 ** 6)
def compute_next_day(t, R, I, S):
R[t] = gamma * I[t - 1] + R[t - 1]
I[t] = (beta * I[t - 1] * S[t - 1] / (r + i + s)) - gamma * I[t - 1] + I[t - 1]
S[t] = - (beta * I[t - 1] * S[t - 1] / (r + i + s)) + S[t - 1]
return [S[t-1], I[t-1], R[t-1]]
def compute_entire_period(Tstart, Tend, R, I, S):
R[Tstart] = r
I[Tstart] = i
S[Tstart] = s
with open('mydata.csv', 'w') as mycsvfile:
writer = csv.writer(mycsvfile)
for t in range(Tstart + 1, Tend):
writer.writerow(compute_next_day(t, R, I, S))
R = range(Tstart, Tend)
I = range(Tstart, Tend)
S = range(Tstart, Tend)
compute_entire_period(Tstart, Tend, R, I, S)