[英]I am trying to perform the Euler method in python but I am getting a 'type error', why?
我正在嘗試使用 Euler 方法解決 python 中的 ODE,但是當我調用 ZC1C425268E68385D1AB5074C17A94 時,我收到“TypeError: 'float' object is not subscriptable”錯誤。 這是我的代碼:
##Parameters
g = 9.8 #in m/s^2
l = 0.5 #in m
omega0 = np.sqrt(g/l)
def euler(theta0, w0, deltat, t_end):
t0 = 0 #in s
##Constructing the arrays
t_arr = np.arange(t0, t_end + deltat, deltat)
w = np.zeros(len(t_arr)) #angular velocity in rad/s
theta = np.zeros(len(t_arr))
##Setting up our initial conditions
w[0] = w0
theta = theta0
##Performing the Euler method for both small and large angles
for i in range(len(t_arr) -1):
w[i + 1] = w[i] - ((omega0)**2)*np.sin(theta[i])*deltat
theta[i + 1] = theta[i] + w[i]*deltat
return theta
euler(0.07, 0, 0.05, 5)
Output:
TypeError: 'float' object is not subscriptable
我究竟做錯了什么? 請幫助,您的幫助將不勝感激。
兩條線
theta = np.zeros(len(t_arr))
...
theta = theta0
彼此接近沒有意義,並且表明它們的含義存在誤解,因為兩者都在變量theta
中放置了一個值。 即第一個沒有任何效果。 第二行是唯一相關的。
我假設變量theta
應該包含一個numpy
數組。 但是你在最后一行的調用中作為參數theta0
的值傳遞的只是一個浮點值,所以這相矛盾。
我猜您可能希望將theta0
放入剛剛創建的數組theta
的第一個字段中:
theta[0] = theta0
可能它會起作用。
您打算在設置初始條件時設置theta[0] = theta0
(第 16 行),但是您只需編寫theta = theta0
而不是之前創建的 np.zeros 數組,就將 theta 重新定義為浮點數第 12 行。改變它,它會工作。
'not subscriptable' TypeError 並不是一種特別容易理解的錯誤解釋方式。 如果您想了解有關這意味着什么的更多詳細信息,請閱讀此問題。 投票最多的答案是:
基本上就是說object實現了getitem ()方法。 換句話說,它描述的是“容器”的對象,這意味着它們包含其他對象。 這包括字符串、列表、元組和字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.