Numpy广播报错:operands could not be broadcast together shapes (0,) (10,)求解
问题根因
- 循环变量
t从0开始迭代,Python切片语法中[:-0]等价于[:0],会返回从起始位置到第0位前的空数组,和你打印的old_capital为空的结果一致。 - 长度为0的空数组(shape为
(0,))和长度为10的current_capital(shape为(10,))形状不匹配,无法执行逐元素算术运算,因此触发广播报错。
修复方案
调整t=0时的切片逻辑,保证old_capital和current_capital长度一致即可,修改后的代码如下:
for t in range(0, timePeriod): for i in range(n): # t=0时直接取完整的Capital_m,避免返回空数组 old_capital = Capital_m[:-t] if t > 0 else Capital_m[:] current_capital = Capital[:] Capital_m[:] = memory * old_capital + (1 - memory) * current_capital
如果你的业务逻辑中t从1开始计数更合理,也可以直接把循环起始值改为1:for t in range(1, timePeriod):,同样能规避这个问题。
内容的提问来源于stack exchange,提问作者ChP
相关产品推荐
相关产品推荐

