如何將 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))
uj5u.com熱心網友回復:
由于一切都是代數,因此很難理解您要做什么,但我認為您希望最終結果是與每個時間單位相對應的 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
uj5u.com熱心網友回復:
如果要在變數中存盤多個值,請使用串列
z 在您的代碼中被宣告為一個串列,其中 z = []
您可以使用 append 方法簡單地添加到串列中
z.append(value)
在你的代碼中
z=[]
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)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/357326.html
上一篇:ruby嵌套for回圈
下一篇:如何檢查字串是否包含任何串列的元素|TypeError:'in<string>'需要字串作為左運算元,而不是串列|初學者問題
