错误:使用序列设置数组

时间:2017-11-22 19:42:53

标签: python arrays python-3.x numpy

import numpy as np

# constants
n=1000                  # number of time steps to simulate
m=90                    # number of angles
rho=1.225               # kg/m^3
g=-9.8                  # m/s^2
start=0.0               # seconds
end=10                  # seconds
initial_velocity=70     # meters/second
initial_height=5

# object
A=.8            # surface area m^2
C=1.4           # drag coefficient
mass=65         # mass of object in kg

# parameters of simulation
angles=np.array([i for i in range(1,m+1)])
radians=np.radians(angles)

#initalize state variables
t=np.linspace(start,end,n+1)
vx=np.zeros((m,n+1),dtype=np.float64)
vy=np.zeros((m,n+1),dtype=np.float64)
x=np.zeros((m,n+1),dtype=np.float64)
y=np.zeros((m,n+1),dtype=np.float64)

for i in range(m):
        y[i][0]=initial_height
        vx[i][0]=initial_velocity*np.cos(radians[i])
        vy[i][0]=initial_velocity*np.sin(radians[i])

# begin simulation
for i in range(m):
    for j in range(1,n+1):
        if y[i,j-1]<=0:
            vx[i,j]=0
            vy[i,j]=0
            y[i,j]=0
            x[i,j]=x[i,j-1]
        else:
            # the following code is _corrected_ from the wrong math
            v = np.sqrt( vx[ j-1 ]**2 + vy[ j-1 ]**2 )
            ax = -( 0.5*rho*C*A/mass ) * v**2 * ( vx[ j-1 ] / v )
            ay = g - ( 0.5*rho*C*A/mass ) * v**2 * ( vy[ j-1 ] / v )
            dt=t[j]-t[j-1]
            vx[i,j]=vx[i,j-1]+ax*dt
            vy[i,j]=vy[i,j-1]+ay*dt
            x[i,j]=x[i,j-1]+vx[i,j]*dt
            y[i,j]=y[i,j-1]+vy[i,j]*dt
            if y[i,j]<=0:
                y[i,j]=0
                x[i,j]=x[i,j-1]
                vx[i,j]=0
                vy[i,j]=0

best_distance=0
best_angle=0
for i in range(m):
    if x[i,-1]>best_distance:
        best_distance=x[i,-1]
        best_angle=i+1

问题是我正在尝试使用加速度和之前的速度计算速度,间隔为dt。由于所有表达式都是关于vx [i,j]的数字,这里的问题是什么?请帮忙! vx和vy都是存储一些数据的二维数组,因此要计算包括拖动在内的实际速度。我介绍了v来更好地模拟投影。

1 个答案:

答案 0 :(得分:0)

在我收到您提及的错误时,只需运行您的代码即可查看错误:

ValueError                                Traceback (most recent call last)
<ipython-input-12-2458d409946f> in <module>()
     46             ay = g - ( 0.5*rho*C*A/mass ) * v**2 * ( vy[ j-1 ] / v )
     47             dt=t[j]-t[j-1]
---> 48             vx[i,j]=vx[i,j-1]+ax*dt
     49             vy[i,j]=vy[i,j-1]+ay*dt
     50             x[i,j]=x[i,j-1]+vx[i,j]*dt

ValueError: setting an array element with a sequence.

ax是一个numpy数组:

array([-51.70596988,          nan,          nan, ...,          nan,
                nan,          nan])

因此,当你用标量添加和乘以它时,你仍然得到一个数组,然后你尝试将其分配给vx[i,j],这是一个单独的元素(也就是说,你不能为它分配一个向量) )。也就是说,我在nan中也看到了一堆ax,所以其他东西可能是错的,这个代码的逻辑需要调试。