【问题标题】:Correcting TypeError: object of type 'float' has no len()更正 TypeError:“float”类型的对象没有 len()
【发布时间】:2021-01-23 11:15:47
【问题描述】:

您好,我是 python 新手,我正在尝试对微分方程 d/dt(θi) =ωi + j(Kij sin(θj -θi)) 的总和进行数值积分,i=1,...,N .

仓本模特:

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()。有人可以帮我纠正这个错误吗?

【问题讨论】:

  • 嘿!你能提供一个Minimal Reproducible Example吗?您的代码在当前状态下无法运行,缺少一些缩进。
  • 哦,好吧,我已经编辑了它并在这里粘贴了来自 spyder 的代码

标签: python arrays function


【解决方案1】:

错误 - TypeError: 'float' 类型的对象没有 len(), 这意味着您尝试计算长度的对象没有;没有长度 在这里,第 5 行的代码是len(t),这里的“t”是一个浮点数,意思是十进制数。您无法计算其长度。

在函数中

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”不是您在函数调用期间传递的数组, 如果您在函数定义中打印“t”,它将打印一个浮点值,因此在尝试计算长度时会出现 TypeError。 您可以在这里做一件事,如果您传递的数组的长度保持不变,您可以对其进行硬编码。

如果这不是一个解决方案,那么试着更好地理解这个函数,它在做什么,我已经打印了“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

【讨论】:

  • 对不起,我想定义一个函数,但我在 for 循环中定义了它。我已经编辑过了。
  • 我已经用 np.linspace 定义了 t 来获取一个数组,然后我想用这个数组的长度进行迭代
  • 相应地更改了答案,检查一下。如果有帮助,请点赞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 2019-10-28
相关资源
最近更新 更多