[英]how do I write data to file that came from a function in Python?
I have function that takes in 4 arguments as shown below:我有 function 接受 4 arguments 如下所示:
def Euler(nsteps, k , m , b):
nsteps = int(time_interval/step_size)
# Create empty arrays ready for the values of x and v
x = np.zeros(nsteps)
v = np.zeros(nsteps)
# Choose some initial conditions
x[0] = 0.0
v[0] = -1.0
for i in range(nsteps-1):
# Calculate the acceleration at step i
a = -(k/m)*x[i] - (b/m)*v[i]
# For each configuration at step i, calculate x and v for the later step i+1
x[i+1] = x[i] + v[i]*step_size
v[i+1] = v[i] + a*step_size
return x, v
I want to write x and v to a file but I'm not too sure how.我想将 x 和 v 写入文件,但我不太确定如何。 This is what I have and it doesn't work.
这就是我所拥有的,但它不起作用。 does anyone know how to fix this please?
请问有人知道如何解决这个问题吗?
Euler_method = open('Euler_method.txt' , 'w')
Euler_method.write(Euler(nsteps, k, m, b))
Euler_method.close()
Your function returns a tuple and you can easily write a tuple to an external file if you convert it to string.您的 function 返回一个元组,如果将元组转换为字符串,您可以轻松地将其写入外部文件。 Thus, just change your code:
因此,只需更改您的代码:
Euler_method = open('Euler_method.txt' , 'w')
Euler_method.write(str(Euler(nsteps, k, m, b)))
Euler_method.close()
But it is not clear what your objective is and if this is the right way to accomplish your objective.但不清楚您的目标是什么,以及这是否是实现目标的正确方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.