在while循环中追加数组

时间:2015-12-04 17:01:34

标签: python arrays numpy

我正在尝试将新创建的数组中的值附加到先前创建的数组,然后运行while循环来执行此操作10,000次。以下是我到目前为止的情况:

IndexError: index 2 is out of bounds for axis 0 with size 2

我试图将new_positions和new_velocities数组中新创建的值附加到partpos和partvel数组,但是收到以下错误:

m_all = np.array([1.98e30, 5.972e24]) # the array of masses
N = len(m_all)
x = np.array([0, 0, 0, 1.5e11, 0, 0]) # an array of all the positions
pp_all = np.reshape(x, (N, 3)) # reshapes position array into Nx3 array
v = np.array([0, 0, 0, 0, 29779.5, 0]) # array of velocities
pv_all = np.reshape(v, (N, 3)) # reshapes velocity array into Nx3 array
tf = (2 * np.pi * 1.5e11) / 29779.5 # calculates total time 
dt = tf / 10e4 # calculate the time step

我该如何解决这个问题?以下是输入:

def evolve_particles(pp_all, pv_all, m_all, dt):
""" 
Evolve particles in time via leap-frog integrator scheme. 

Parameters
----------
pp_all : np.ndarray
    2-D array containing (x, y, z) positions for all particles. 
    Shape is (N, 3) where N is the number of particles.
pv_all : np.ndarray
    2-D array containing (x, y, z) velocities for all particles. 
    Shape is (N, 3) where N is the number of particles.
m_all : np.ndarray
    1-D array containing masses for all particles, length N, where
    N is the number of particles.
dt : float
    Evolve system for time dt.

Returns
-------
Updated particle positions and particle velocities, each being a 2-D
array with shape (N, 3), where N is the number of particles.

""" 

# Make copies of position/velocity arrays that we can modify in-place.
pp = pp_all.copy()
pv = pv_all.copy()

N = len(m_all)             # Number of particles in system
dims = pp_all.shape[-1]    # Dimensionality of problem

# Compute net force vectors on all particles
forces = netGravForces(m_all, pp_all)

# Leap-frog method takes two half-steps (first dimension of acc array)
acc = np.zeros([2,N,dims])

# Leap-frog integrator takes two half-steps
step = 0
while step < 2:      

    # Loop over particles, compute acceleration,
    # update positions and velocities
    for k in xrange(N):

        # Rec-calculate acceleration at each half-step
        acc[step,k] = forces[k] / m_all[k]

        # Update position on first half-step, velocity on second
        if step == 0:
            pp[k,:] = pp[k] + pv[k] * dt + 0.5 * acc[0,k] * dt**2
        else:
            pv[k,:] = pv[k] + 0.5 * (acc[0,k] + acc[1,k]) * dt

    step += 1

return pp, pv

此代码应该使用10,000次步骤模拟太阳周围地球的轨道。 new_positions和new_velocities是每个2D数组。谢谢!

这是evolve_particles函数:

IndexError                                Traceback (most recent call last)
<ipython-input-24-843691efebda> in <module>()
----> 1 partpos, partvel = evolve(m_all, pp_all, pv_all, tf, dt)

<ipython-input-22-f0eb2f7f6e98> in evolve(m_all, pp_all, pv_all, tf, dt)
     38         t += dt # add time step
     39         while i < 10000:
---> 40             partpos[i] = new_positions[i]
     41             partvel[i] = new_velocities[i]
     42             i += 1

IndexError: index 2 is out of bounds for axis 0 with size 2

这是产生错误的行的错误消息:

<div class="form-group">
    @Html.LabelFor(model => model.Approved, htmlAttributes: new {@class = "control-label col-md-2"})
    <div class="col-md-2">
        <div class="checkbox">
            @Html.EditorFor(model => model.Approved, new { onclick="SingleCheckbox(this)" })
            @Html.ValidationMessageFor(model => model.Approved, "", new {@class = "text-danger"})
        </div>
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Rejected, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-2">
        <div class="checkbox">
            @Html.EditorFor(model => model.Rejected, new { onclick="SingleCheckbox(this)" })
            @Html.ValidationMessageFor(model => model.Rejected, "", new { @class = "text-danger" })
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

while中的while t < tf循环evolve将重复100,000次。这意味着代码期望new_positions拥有100,000个元素。但是evolve_particles的返回值是仅包含2个元素的列表,因为它基于pp_all输入中的元素数量。所以你在循环第三次得到一个索引错误。