IndexError: list index out of range in Py

Question:

I wrote the python code:

def diff_4(x, h, y):
    """Вычисляет приближенное значение производной с помощью формулы численного дифференцирования для четырех равноудаленных узлов"""
    return (-y[4] + 8*y[2] - 8*y[1] + y[0]) / (12*h)
x = 0.295 # начальное значение x
h = 0.002 # шаг интерполяции
y = [1.96434, 1.96336, 1.97242, 1.98155, 1.99043] # значения параметра y
d1 = diff_4(x, h, y) # вычисляем приближенное значение первой производной
d2 = diff_4(x, h, [diff_4(x, h, y)]) # вычисляем приближенное значение второй производной
print("Первая производная:", d1)
print("Вторая производная:", d2)

But for some reason I get this error:

Traceback (most recent call last):
  File "C:UserspetrrDesktopККРИТАлгоритмизация1.py", line 8, in <module>
    d2 = diff_4(x, h, [diff_4(x, h, y)]) # вычисляем приближенное значение второй производной
  File "C:UserspetrrDesktopККРИТАлгоритмизация1.py", line 3, in diff_4
    return (-y[4] + 8*y[2] - 8*y[1] + y[0]) / (12*h)
IndexError: list index out of range

Process finished with exit code 1

Please help me fix the problem, thank you very much in advance.

I tried changing numbers and format but nothing helps

Answers:

The error message suggests that you are trying to access an index that is out of range in the y list. In the diff_4 function, you are trying to access y[4], which is the fifth element of the list y. However, y only has five elements, so the maximum index you can access is y[4].

To fix this issue, you should change the index 4 to 3 in the diff_4 function, so that it accesses the last element of the y list. Here’s the corrected code:

def diff_4(x, h, y):
    """Вычисляет приближенное значение производной с помощью формулы численного дифференцирования для четырех равноудаленных узлов"""
    return (-y[3] + 8*y[2] - 8*y[1] + y[0]) / (12*h)

x = 0.295 # начальное значение x
h = 0.002 # шаг интерполяции
y = [1.96434, 1.96336, 1.97242, 1.98155, 1.99043] # значения параметра y
d1 = diff_4(x, h, y) # вычисляем приближенное значение первой производной
d2 = diff_4(x, h, [diff_4(x, h, y)]) # вычисляем приближенное значение второй производной
print("Первая производная:", d1)
print("Вторая производная:", d2)

Note that in the calculation of d2, you are passing a list containing a single value diff_4(x, h, y) as the y argument to the diff_4 function. This is not correct, because the diff_4 function expects a list of four values. To fix this, you should pass the original y list as the argument to the second call of diff_4, like this:

d2 = diff_4(x, h, [diff_4(x, h, y), diff_4(x, h, y), diff_4(x, h, y), diff_4(x, h, y)])

This will calculate the second derivative using the first derivative calculated earlier.

Answered By: Marko Hauptman

I see that you list goes like 4, 2, 1, 0.
The correct indices for the y list in your diff_4 function should be 3, 2, 1, and 0, respectively.

Answered By: AlexTrusk