You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

出现IndexError: index out of bounds错误,请求排查代码问题

解决IndexError: index out of bounds的问题

嘿,这个错误的原因一眼就能看出来啦!你看:

  • 你的循环是基于x_particle_position的长度(要跑5000次迭代)
  • 但delta_translation_hat和delta_rotation_1_hat只有1000个元素

当循环运行到i >= 1000的时候,你尝试访问delta_translation_hat[i]或者delta_rotation_1_hat[i],这两个数组根本没有这么靠后的索引,自然就触发了越界错误。

接下来给你几种针对性的解决方案,你可以根据实际需求选择:

方案1:循环复用短数组的元素

如果这两个短数组是需要重复应用到所有5000个粒子上的,那可以用取模运算来循环获取它们的元素:

import numpy as np

for i in range(len(x_particle_position)):
    # 用取模确保索引始终在短数组的范围内
    trans_idx = i % len(delta_translation_hat)
    rot_idx = i % len(delta_rotation_1_hat)
    x_particle_position[i] += delta_translation_hat[trans_idx] * (np.cos(particle_heading_list[i] + delta_rotation_1_hat[rot_idx]))
    print("X is", x_particle_position[i])

方案2:让短数组和其他数组长度一致

如果本来delta_translation_hat和delta_rotation_1_hat就应该是5000长度的,那你需要检查生成这两个数组的代码,确保它们的长度和x_particle_position、particle_heading_list匹配。比如可以用numpy的重复方法扩展数组:

# 示例:把短数组重复5次,变成5000长度
delta_translation_hat = np.tile(delta_translation_hat, 5)
delta_rotation_1_hat = np.tile(delta_rotation_1_hat, 5)

方案3:只循环短数组的长度

如果实际上你只需要处理前1000个粒子,那直接把循环范围改成短数组的长度就行:

for i in range(len(delta_translation_hat)):
    x_particle_position[i] += delta_translation_hat[i] * (np.cos(particle_heading_list[i] + delta_rotation_1_hat[i]))
    print("X is", x_particle_position[i])

内容的提问来源于stack exchange,提问作者Eslam Elgourany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:47:41