如何將 z 存儲為具有多個值的變量,而不是在每次循環後重寫 z 的代碼?
import numpy as np
def equation1(m,k,x,deltat):
Fpeak = 1000 + 9 * x**2 - 183 * x
td = 20 - 0.12 * x**2 + 4.2 * x
w = np.sqrt(k/m)
T = 2 * np.pi / w
time = np.arange(0,2*T,deltat)
z=[]
for t in time:
if (t <= td):
z = (Fpeak/k) * (1 - np.cos(w*t)) + (Fpeak/k*td) * ((np.sin(w*t)/w) - t)
else:
z = (Fpeak/(k*w*td)) * (np.sin(w*t) - np.sin(w*(t-td))) - ((Fpeak/k) * np.cos(w*t))
return(z)
print(equation1(200,1000,0,0.001))
由於一切都是代數,因此很難理解您要做什麼,但我認為您希望最終結果是與每個時間單位相對應的 z 值列表?
在這種情況下,將每個 'z = ...' 行替換為 'z.append(...)' 並取消縮進 return 語句,因此它在函數的範圍內,而不是在 for 循環中。
...
def a_more_descriptive_function_name(m,k,x,deltat):
# ...
for t in time:
if (t <= td):
z.append((Fpeak/k) * (1 - np.cos(w*t)) + (Fpeak/k*td) * ((np.sin(w*t)/w) - t))
else:
z.append((Fpeak/(k*w*td)) * (np.sin(w*t) - np.sin(w*(t-td))) - ((Fpeak/k) * np.cos(w*t)))
return z
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句