It's uncomfortable code, I know, and sorry. Especially, if it's a stupid question.
Here is an error with list, and I don't know why (I'm beginner). Can someone, please, tell me, how to fix it?
This is the output:
Traceback (most recent call last):
File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 77, in <module>
vx, vy = rk3(diff1, 0, U0, 10, 100)
File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 39, in rk3
x,v=step(f, h, i, x0, U0)
File "C:/Users/milom/PycharmProjects/ChislM/method.py", line 11, in step
k2 = f(x[i] + (1 / 3) * h[i], v[i] + (1 / 3) * k1)
IndexError: list index out of range
Code:
import matplotlib.pyplot as plt
import math as m
import pandas as pd
x =[0]*101
v =[0]*101
def step(f, h, i, x0, U0):
x[0] = x0
v[0] = U0
k1 = f(x[i], v[i])
k2 = f(x[i] + (1 / 3) * h[i], v[i] + (1 / 3) * k1)
k3 = f(x[i] + (2 / 3) * h[i], v[i] + (2 / 3) * h[i] * k2)
x[i] = x[i - 1] + h[i]
v[i] = v[i - 1] + (h[i]) * ((1 / 4) * k1 + (3 / 4) * k3)
return x, v
def rk3(f, x0, U0, x1, n):
h = [(x1 - x0) / float(n)]
for i in range(1, n+1):
x,v=step(f, h, i, x0, U0)
###h= control(f, h[i], i, v[i], x0, U0)
return x, v
def diff1(x, U):
return 0.1
def diff(x, U):
return -(m.cos(10 * x) + ((m.log(1 + x ** 2)) / (1 + x)) * (U ** 2) + U)
def exact_path():
plt.grid()
plt.plot(vx, vy)
plt.show()
def table():
mytable = pd.DataFrame({
'Xn': vx,
'Vn': vy,
}, index=[i for i in range(0, 101)])
mytable.index.name = 'number'
pd.set_option('display.max_rows', None)
print(mytable)
task = int(input("Task:"))
U0 = float(input("First value- U0:"))
if task == 2:
vx, vy = rk3(diff, 0, U0, 10, 100)
table()
exact_path()
if task == 1:
vx, vy = rk3(diff1, 0, U0, 10, 100)
table()
exact_path()
PS It's a simple 3th order Runge-Kutta method, but mostly problem with synthax. I tried to implement method with Python.
In the rk3()
function you have h = [(x1 - x0) / float(n)]
which creates an list with only a single element in it. This means that the only valid non-negative index that can be used with it would be h[0]
—and an attempt to use any other index value, as is likely in the step()
function in the for
loop, will cause an IndexError
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.