【发布时间】:2016-11-11 05:19:53
【问题描述】:
我有两个函数,一个使用 Runge-Kutta 方法(或中点方法)和 Euler 方法来求解微分方程。然而,它应该解决的功能并不能让它发挥作用。 我得到了错误:
TypeError: 'float' object is not subscriptable
这是我的代码
def integrateMidpoint(f, x0, t0, h, N):
mpxaxis = [0] * (N + 1)
mpyaxis = [0] * (N + 1)
mpxaxis[0] = t = t0
mpyaxis[0] = x = x0
for x in x0:
for i in range(1, N +1):
k1 = h * f(t, x)
k2 = h * f(t + 0.5 * h, x + 0.5 * k1)
mpxaxis[i] = t= t0 + i * h
x = x + k2
mpyaxis[i] = [x]
return mpxaxis, mpyaxis
def integrateEuler(f,x0,t0,h,N):
t = t0
xaxislist = []
yaxislist = []
Finalxaxisvalue = N*h # #ofsteps * stepsize
for x in x0:
while t <= Finalxaxisvalue:
xval = t
yval = x
t += h
x += h * f(t,x)
xaxislist.append(xval)
yaxislist.append(yval)
return xaxislist, yaxislist
def f(t,x):
return [-x[0]**3 - x[0] + sin(t)] #returns a list
我尝试了列表理解,在欧拉函数中我用
替换了它x += [h*i for i in f(t,x)]
但我仍然在同一行中遇到相同的错误。最初我的程序使用像这样编码的f(t,x) 函数
return -x**3 - x + sin(t)
我得到一个列表的返回值和列表的列表。但是有了这个带维度的新功能,我想知道我该怎么做呢?列表理解不起作用。我不明白为什么,因为我使用了函数f(t,x) 中返回的列表中的值。
在shell中我输入:
>>>integrateEuler(f, [0.], 0., 1., 10)
>>>Traceback (most recent call last):
Python Shell, prompt 2, line 1
File "redacted.py", line 13, in <module>
multt = [h * i[0] for i in f(t,x)]
File "redacted.py", line 21, in <module>
return [-x[0]**3 - x[0] + sin(t)]
builtins.TypeError: 'float' object is not subscriptable
其中f是一个函数,x0是时间t0的初始条件,t0是初始时间,h是步长,N是步数。
【问题讨论】:
-
你没有提供
Euler功能码。 -
我很抱歉我很懒惰,但我将它缩短为欧拉,它最初是集成欧拉。我现在重新编辑一下
标签: python list python-3.x list-comprehension