在循环中使用浮点数列表

Using a list of floats for a loop

我正在尝试 运行 Runge-Kutta 算法来逼近微分方程。我想遍历函数中常量变量 A 的值列表,并让算法循环遍历列表中的每个项目并生成一个图形。我一直收到一条错误消息 "list indices must be integers or slices but not a float"。我试图将列表中的数字转换为彼此的整数分数,但这也不起作用。我不确定如何规避此错误,因为我发现一些修复无效,这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from math import pi
from numpy import arange
from matplotlib.pyplot import plot,show

wo = 1
w = 2       #defining wo, w, g1, Amplitude and steps
h = 0.001
g1 = 0.2
A = [0.1,0.25,0.5,0.7,0.75,0.85,0.95,1.00,1.02,1.031,1.033,1.035,1.05]
for item in list(A):                #Converting list items into Float values
    [float(i) for i in A]

xpoints = arange(0,100,h)
tpoints = []
zpoints = []
t=0
x = 0
z = pi/2
for i in A:                               #Calls for items in Amplitude list to run algorighm
    def F(t, z, x):                             #Defining the differential equation
        return -g1 * z - (wo ** 2 + 2 * A[i] * np.cos(w * t)) * np.sin(x)
    for x in xpoints:
        tpoints.append(t)
        zpoints.append(z)
        m1 = z*h
        k1 = h*F(t,z,x)    #setting up the runge-kutta algorithm
        m2 = h*(z+(k1/2))
        k2 = h*F(t+0.5*m1,z+0.5*m1,x+0.5*h)
        m3 = h*(z+0.5*k2)
        k3 = h*F(t+0.5*m2,z+0.5*m2,x+0.5*h)
        m4 = h*(z+0.5*k3)
        k4 = h*F(t+0.5*m3,z+0.5*m3,x+0.5*h)
        t += (m1+2*m2+2*m3+m4)/6
        z += (k1+2*k2+2*k3+k4)/6
    A += 1
plot(xpoints,zpoints)

问题不在于数字本身需要转换。请注意您如何使用 for i in A: 进行迭代。这意味着 i 是实际值而不是索引。因此,在您使用 A[i] 的地方,您试图转到 A 的 0.1 索引。相反,只需将此代码段底部行中的 A[i] 替换为 i。

A = [0.1,0.25,0.5,0.7,0.75,0.85,0.95,1.00,1.02,1.031,1.033,1.035,1.05]
...
for i in A:      
    def F(t, z, x):                             
        return -g1 * z - (wo ** 2 + 2 * A[i] * np.cos(w * t)) * np.sin(x)

因为i的值是A的一个元素,如果要在A列表中逐个索引循环:

for i in range(len(A))

这行得通。

这次A+=1出错,我想这个地方会是i+=1。