python - 索引 4 超出了轴 1 的范围,尺寸为 4 带有双和的代码

标签 python bounds out

您好,我有以下函数会产生越界错误:

import numpy as np
import pylab as plt
import scipy
import math
import sympy as sy


T = sy.Symbol('T')
rho = sy.Symbol('rho')


g_T   = [1,T,T**2,T*sy.log(T),T**2*sy.log(T)]
g_rho  = [1,rho,rho**2,rho*sy.log(rho),rho**2*sy.log(rho)]

g_T_np = np.asarray(g_T)
g_rho_np = np.asarray(g_rho)


c = np.loadtxt("c_test.txt")


def F(T,rho):
    ret = 0
    for n in xrange(1,5):
        for m in xrange(1,6):
            inner= c[n,m]*g_T_np*g_rho_np
        ret += inner
    return ret

print F(T,rho)

其中.txt文件是这样的:

-0.529586   -0.000208559    -3.36563E-09    2.29441E-05 
2.22722E-06 -0.00014526 -2.48888E-09    1.89488E-05 
-6.26662E-05    0.000421028 6.17407E-09 -5.14488E-05    
0.09977346  -0.000622051    -8.56485E-09    7.49956E-05 
-0.01437627 -9.86754E-05    -1.59808E-09    1.22574E-05

显示的完整错误是:

Traceback (most recent call last):File "EOS_test.py", line 38, in <module> print F(T,rho) File "EOS_test.py", line 31, in F inner=c[n,m]*g_T_np*g_rho_np IndexError: index 4 is out of bounds for axis 1 with size 4

我该如何解决这个错误?

最佳答案

Numpy 使用基于 0 的索引。从它的外观来看,您正在将数组从 1(第 2 个位置)索引到 4(第 5 个位置),这当然超出了您正在使用的数组的范围。第二个轴也是如此。

其次,你弄错了坐标轴:

  • 第一个轴(0)是所选行的索引(0 到 5)
  • 第二个轴索引列,即行内的值(索引 0 到 4)

这应该有效:

def F(T,rho):
    ret = 0
    for n in range(5):
        for m in range(4):
            inner= c[n,m]*g_T_np*g_rho_np
        ret += inner
    return ret

关于python - 索引 4 超出了轴 1 的范围,尺寸为 4 带有双和的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593205/

相关文章:

python - Django : How to import a data from csv to database without using form?

python - numpy.where 用于 2+ 个特定值

python - 如何在 Scikit-learn 中获取 OneHotEncoder 的维度数

c - 夹板边界检查的奇怪行为

actionscript-3 - AS3 : weird getBounds() result

python - 如何在 python 中从全局范围运行 "exec"

java - 错误: incompatible types: inference variable R has incompatible bounds (Lambda java 8)

filter - 如何过滤给定列的行(不为null)?

c# - 如何重写 bool TrySomething(List<T> items, out List<T> itemsThatFailed)

c# - 从 C# 调用 C++/CLI(不带 out 参数)