python - 继续收到太多无法插入数组的索引

标签 python arrays numpy debugging error-handling

interp-使用Lagrange插值数据的程序

我无法按照下面的编码顺序完成for循环。我没有发现任何问题,因为我选择np.empty(nplot)为xi创建1D数组,并且由于某种原因,循环不会填充这些值。

def intrpf(xi,x,y):
    """Function to interpolate between data points
       using Lagrange polynomial (quadratic)
       Inputs
        x    Vector of x coordinates of data points (3 values)
        y    Vector of y coordinates of data points (3 values)
        xi   The x value where interpolation is computed
      Output
        yi   The interpolation polynomial evaluated at xi
    """

#* Calculate yi = p(xi) using Lagrange polynomial
    yi = ( (xi-x[1])*(xi-x[2])/((x[0]-x[1])*(x[0]-x[2])) * y[0]
    + (xi-x[0])*(xi-x[2])/((x[1]-x[0])*(x[1]-x[2])) * y[1]
    + (xi-x[0])*(xi-x[1])/((x[2]-x[0])*(x[2]-x[1])) * y[2] )
    return yi

#* Initialize the data points to be fit by quadratic
x = np.empty(3)
y = np.empty(3)
print ('Enter data points as x,y pairs (e.g., [1, 2]')
for i in range(3):
    temp = np.array(input('Enter data point: '))
    x[i] = temp[0]
    y[i] = temp[1]

#* Establish the range of interpolation (from x_min to x_max)
xr = np.array(input('Enter range of x values as [x_min, x_max]: '))


我被这部分卡住了,似乎已经正确设置了,但是在for循环中的xi [i]上出现了“数组的索引过多”。
#* Find yi for the desired interpolation values xi using
#  the function intrpf
nplot = 100     # Number of points for interpolation curve
xi = np.empty(nplot)
yi = np.empty(nplot)
for i in range(nplot) :
    xi[i] = xr[0] + (xr[1]-xr[0])* i/float(nplot)
    yi[i] = intrpf(xi[i], x, y)    # Use intrpf function to interpolate

最佳答案

np.array的文档中:

Parameters:

object: _array_like_

An array, any object exposing the array interface, an object whose array method returns an array, or any (nested) sequence.



这意味着数组应该接受类似于列表的内容以进行转换,而输入则返回字符串。 python到底要在这里做什么?
np.array('[1, 2]')

虽然可能很想做类似的事情
np.array(eval(input()))

绝对不要这样做,因为它是不安全的,因为它允许用户在程序中执行任何类型的代码。如果您真的需要这种输入,我会建议类似
np.array(list(map(int, input('Enter data point: ')
                       .replace('[','')
                       .replace(']','')
                       .split(','))))

关于python - 继续收到太多无法插入数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62314332/

相关文章:

python - Beautiful Soup - 从 div 类内的外部引号中提取值

python - 两个不同长度数组的总和

python - 如何检查对象是列表还是元组(但不是字符串)?

python - 在 NumPy 中对数组进行排序,在一列上升序,在另一列上降序

java - 将单词的字符添加到 JButtons 中

python - 起始值和最小值/最大值之间的随机游走序列

python - Virtualenv 和 Pip 永远挂起

c - 如何正确初始化/访问具有多个源的结构数组?

python - 根据其他两列的 bool 值返回一个 bool 值

python - 屏蔽掉数组中的特定值