错误“无法将序列与'float'类型的非整数相乘”

2024-06-26 08:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,当我尝试运行行“x01=rk4(x01,t1[-1],h1,fallParabola)”时,会弹出一个错误,说“不能用‘float’类型的非int乘以sequence”。我想知道这是为什么,因为我认为numpy数组中的每一项乘以一个数,数组中的每一项乘以那个数。你知道吗

**slope1和intercept1已经在别处定义,所以这不是问题

def rk4(f,t,h,g):
    k1 = h*g(t,f)
    k2 = h*g(t+0.5*h, f+0.5*k1)
    k3 = h*g(t+0.5*h, f+0.5*k2)
    k4 = h*g(t+h, f+k3)
    return f + k1/6. + k2/3. + k3/3. + k4/6.

def fallParabola(t,f):
    g = 10
    px = f[0]
    py = f[1]
    vx = f[2]
    vy = f[3]
    slope = slope1 * (px-shift1)
    theta = sp.arctan(np.abs(slope))
    acc = np.array([vx,vy,g*sp.sin(theta)*sp.cos(theta), 
        g*sp.sin(theta)*sp.sin(theta)])
    return acc,slope

x01 = np.array([0.0,intercept1,0.0,0.0])
t01 = 0.
px1 = [x01[0],]
py1 = [x01[1],]
vx1 = [x01[2],]
vy1 = [x01[3],]
t1 = [t01,]
h1 = 0.1
while py1[-1] > 0:
    x01 = rk4(x01,t1[-1],h1,fallParabola)
    px1.append(x01[0])
    py1.append(x01[1])
    vx1.append(x01[2])
    vy1.append(x01[3])
    t1.append(t1[-1]+h1)

Tags: npk2k1sinh1spslopet1
1条回答
网友
1楼 · 发布于 2024-06-26 08:20:19

您将h乘以一个元组,而不是Runge-Kutta定义中的numpy数组:

def rk4(f,t,h,g):
    k1 = h*g(t,f)
    k2 = h*g(t+0.5*h, f+0.5*k1)
    k3 = h*g(t+0.5*h, f+0.5*k2)
    k4 = h*g(t+h, f+k3)
    return f + k1/6. + k2/3. + k3/3. + k4/6.

这里g是您要传递的函数,它是fallParabola(),根据您的定义,它返回一个元组:

def fallParabola(t,f):
    g = 10
    px = f[0]
    py = f[1]
    vx = f[2]
    vy = f[3]
    slope = slope1 * (px-shift1)
    theta = sp.arctan(np.abs(slope))
    acc = np.array([vx,vy,g*sp.sin(theta)*sp.cos(theta), 
        g*sp.sin(theta)*sp.sin(theta)])
    return acc,slope

您应该修改此定义以返回numpy数组,以便可以对其进行乘法:

return np.array([acc, slope])

关于non int的特定错误消息的原因很简单,因为您可以将一个元组乘以一个整数,但这不会将元组中的值相乘。首先,元组是不可变的,因此无论如何都不能更改值,但一般来说,对于序列,乘以整数会重复序列乘以乘数。例如

>>> tup = (5, 4)
>>> tup*3
(5, 4, 5, 4, 5, 4)

如果你在这里乘以一个浮点数,那就毫无意义了,你会得到同样的错误:

>>> tup*3.14
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

另外,您的fallParabola()函数在IMO中没有很好的定义。目前您的函数使用全局变量(如slope1shift1),但最好将这些值传递到函数中。一般来说,全局变量在Python中并不是有害的,但是如果一个函数使用了一些参数,那么最好将这些参数发送进来,这样您就知道它在使用什么了。如果您需要随着时间的推移更新变量,比如slope1,这提供了一个更简单的接口。你知道吗

相关问题 更多 >