纠正TypeError:“ float”类型的对象没有len()

时间:2020-10-08 11:55:28

标签: python arrays function

嗨,我是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()。有人可以帮我纠正此错误吗?

1 个答案:

答案 0 :(得分:1)

错误- TypeError:“ float”类型的对象没有len(), 这意味着您要计算长度的对象没有长度 此处,第5行的代码为import React from "react"; import { render } from "@testing-library/react"; import { Provider } from "react-redux"; import Header from "../../components/header/Header"; import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); const store = mockStore({ sidebar: { toggle: false }, settingsUi: { title: "Test" }, }); describe("<Header/>", () => { it("test title", () => { const { getByText } = render( <Provider store={store}> <Header /> </Provider>, ); expect(getByText("Test")).toBeInTheDocument(); }); }); ,此处的“ t”为浮点数,表示十进制数。您无法计算长度。

在功能中

len(t)

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

如果这不是解决方案,请尝试更好地了解该函数的功能,正在执行的操作,我已打印“ 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”中的内容

引用:https://apmonitor.com/pdc/index.php/Main/SolveDifferentialEquations