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

Python运行报IndexError索引越界,calculateFunction方法报错如何解决

问题原因&修复方案
  • 索引越界核心原因:generateCandidateVector函数中np.random.choice返回的是种群数组的下标,不是下标对应的二维坐标向量,你直接用下标数值计算候选向量vectorZ,得到的是只有1个元素的数组,传入目标函数访问x[1]自然触发越界。
  • 语法警告原因:目标函数计算行return (x[0]-1)**2+5(x[1]-x[0]**2)**2不符合Python语法,数值和括号之间的乘号不能省略,需要写为5*(x[1]-x[0]**2)**2。
  • 其余逻辑问题:
    • 候选向量更优时的替换逻辑写反,当前代码是把原种群的旧向量赋值给vectorZ,应该是把更优的vectorZ存入新种群
    • 新种群数组populationOneArray初始化形状错误,需要和原种群一致为(N-1,2)
    • 初始种群的双重循环逻辑冗余,可直接向量化生成
    • 递归调用generateCandidateVector时参数不全,迭代逻辑不符合需求,改为循环迭代即可
修正后可运行代码
import numpy as np

def calculateFunctionValue(x):
    # 补全乘号
    return (x[0]-1)**2 + 5*(x[1]-x[0]**2)**2

def x0x1Array(N, F, K):
    # 直接向量化生成初始坐标,不需要嵌套循环
    x0 = np.random.uniform(-2, 2, size=N-1)
    x1 = np.random.uniform(-2, 2, size=N-1)
    x0x1 = np.column_stack((x0, x1))
    generateCandidateVector(x0x1, N, F, K)

def generateCandidateVector(newPopulationArray, N, F, K):
    generation = 0
    current_pop = newPopulationArray.copy()
    while generation <= K:
        # 初始化新种群,形状和原种群一致
        new_pop = np.zeros_like(current_pop)
        for i in range(len(current_pop)):
            # 选3个不重复的索引
            idx = np.random.choice(len(current_pop), 3, replace=False)
            # 用索引取对应的坐标向量
            x0_vec = current_pop[idx[0]]
            x1_vec = current_pop[idx[1]]
            x2_vec = current_pop[idx[2]]
            # 计算候选向量
            vectorZ = x0_vec + F * (x1_vec - x2_vec)
            # 对比函数值,更优则替换
            if calculateFunctionValue(vectorZ) < calculateFunctionValue(current_pop[i]):
                new_pop[i] = vectorZ
            else:
                new_pop[i] = current_pop[i]
        current_pop = new_pop
        generation += 1
    # 迭代结束后找最优解
    func_values = np.array([calculateFunctionValue(vec) for vec in current_pop])
    best_idx = np.argmin(func_values)
    print("最优坐标:", current_pop[best_idx])
    print("最小函数值:", func_values[best_idx])

def main():
    K = 50
    F = 0.8
    N = 50
    x0x1Array(N, F, K)

if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者Weightlifting Without Limits

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:15:03