[英]Correcting TypeError: object of type 'float' has no len()
嗨,我是 python 的新手,我正在尝试对微分方程 d/dt(θi) =ωi + j( Kij sin(θj −θi)), i=1,...,N 求和进行数值积分。
仓本 model:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def kuramoto(theta,t):
N = len(t)
w = np.array([0.1,0.2,0.3,0.4])
K = np.random.rand(N,N)
for i in range (0,N-1):
sum = K[i][i+1]*np.sin(theta[i+1]-theta[i])
sum = sum + K[i][i-1]*np.sin(theta[i-1]-theta[i])
theta_dot = w[i] + (1/N)*sum
return theta_dot
t = np.linspace(0,40,40)
theta0 = [(0.2,0.4,0.3,1.2)]
for theta0 in [(0.2,0.4,0.3,1.2)]:
y_true = odeint(kuramoto,theta0,t)
plt.plot(t,y_true,'r-')
但是,我不断收到错误TypeError: object of type 'float' has no len()
。 有人可以帮我纠正这个错误吗?
错误 - TypeError: object of type 'float' has no len() ,这意味着您尝试计算长度的 object 没有;没有长度在这里,第 5 行的代码是len(t)
这里的“t”是一个浮点数,表示十进制数。 你无法计算它的长度。
在 function
def kuramoto(theta,t):
N = len(t)
w = np.array([0.1,0.2,0.3,0.4])
K = np.random.rand(N,N)
第二个参数 - “t”不是您在 function 调用期间传递的数组,如果您在 function 定义中打印“t”,它将打印一个浮点值,因此在尝试计算长度时会出现 TypeError。 您可以在这里做一件事,如果您传递的数组的长度保持不变,您可以对其进行硬编码。
如果这不是解决方案,那么请尝试更好地了解 function,它在做什么,我打印了“t”以便您了解其中传递的内容。 试试这个代码
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# function that returns dy/dt
def model(y,t):
print("t=",t)
k = 0.3
dydt = -k * y
return dydt
# initial condition
y0 = 5
# time points
t = np.linspace(0,20)
# solve ODE
y = odeint(model,y0,t)
# plot results
plt.plot(t,y)
plt.xlabel('time')
plt.ylabel('y(t)')
plt.show()
你会知道“t”中存储了什么
参考: https://apmonitor.com/pdc/index.php/Main/SolveDifferentialEquations
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.