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

拉格朗日插值函数出现索引越界错误(index 9 is out of bounds for axis 0 with size 9)的原因及修复方案

Fixing Your Lagrange Interpolation Index Error & Code Issues

Let's walk through why you're hitting that index error and fix up your Lagrange interpolation code properly.

Why You're Getting the "Index Out of Bounds" Error

Your core problem is the loop range:

  • d = len(b) gives you 9 (since b = np.arange(3,12) creates 9 elements: 3-11 inclusive)
  • You're using range(d+1) in both loops, which runs from 0 to 9 (10 iterations total)
  • But your arrays b and y only have indices from 0 to 8 (since their size is 9). When i or j hits 9, trying to access x[i] or x[j] triggers the index out of bounds error.

That's the immediate culprit, but there are a few other logic issues in the code that need fixing too.

Full Fixes for Your Code

Here's the corrected version with explanations of each change:

import numpy as np
from sympy import Symbol

t = Symbol('t')

def interpolation(x, z):
    if len(x) != len(z):
        print("Error: the length of x and z is different")
        return  # Exit function if lengths don't match
    d = len(x)  # Move d inside the function to use input x's length
    L = 0
    # Use range(d) instead of range(d+1) to iterate over valid indices (0 to d-1)
    for i in range(d):
        p = 1
        for j in range(d):
            if j != i:
                # Fix parentheses: (t - x[j]) divided by (x[i] - x[j])
                p *= (t - x[j]) / (x[i] - x[j])
        L += z[i] * p
    return L  # Return the interpolation expression

# Test the function
b = np.arange(3,12)
y = np.arange(9)
result = interpolation(b, y)
print(result)

Key Changes Made:

  • Fixed loop ranges: Switched range(d+1) to range(d) so we only iterate over valid indices (0 to 8 for your 9-element arrays)
  • Corrected Lagrange base function: Fixed the parentheses around (t - x[j]) — your original code was calculating t - (x[j]/(x[i]-x[j])) instead of the correct (t - x[j])/(x[i] - x[j])
  • Moved d inside the function: Now it uses the length of the input x instead of relying on an external variable, making the function reusable for any input arrays
  • Added return statement: The function now returns the interpolation expression instead of calculating it and discarding it (your original code printed None because there was no return)
  • Added early exit: If x and z have mismatched lengths, the function prints the error and exits immediately instead of continuing

Testing the Fixed Code

When you run this corrected version, it will output the proper Lagrange interpolation polynomial in terms of t without any index errors.

内容的提问来源于stack exchange,提问作者Ryan McAree

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 23:07:43