拉格朗日插值函数出现索引越界错误(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 (sinceb = 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
bandyonly have indices from 0 to 8 (since their size is 9). Wheniorjhits 9, trying to accessx[i]orx[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)torange(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 calculatingt - (x[j]/(x[i]-x[j]))instead of the correct(t - x[j])/(x[i] - x[j]) - Moved
dinside the function: Now it uses the length of the inputxinstead 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
Nonebecause there was no return) - Added early exit: If
xandzhave 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
相关产品推荐
相关产品推荐

