【问题标题】:solving coupled differential equations with a periodically changing constant in the function with python用python在函数中求解具有周期性变化常数的耦合微分方程
【发布时间】:2022-07-22 01:25:03
【问题描述】:

我正在求解一个耦合微分方程组,微分方程中的一个“常数”实际上是一个周期性变化的值:周期的前半部分的值为 1,周期的其余部分的值为为 0,周期为 2pi。

我将该常数的值设置为平方函数(使用平方函数代码和 if else 代码),并使用 odeint 求解微分方程。

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
from scipy import signal
u=0.3
def l(f):
    if int(2*t)%2np.pi == 0:
        return 1
    else:
        return -1


def model(theta,t):   

    j = theta[0]
    x = theta[1]
    p = theta[2]
    
    dJ_dt = 2*l(f)*(math.sqrt(2))*x*j
    dX_dt = p-(k/2)*x
    dP_dt = -x-(k/2)*p-2*l(f)*(math.sqrt(2))*j
    
    dtheta_dt = [dJ_dt, dX_dt, dP_dt]
    return dtheta_dt

theta_0 = [0.5*math.sqrt(1-u**2), 0, -0.5*u, 0, 0]

t = np.linspace(0,5000,1000)

theta = odeint(model,theta_0,t)

plt.figure(figsize=(25,8))
plt.plot(t, theta[:,0],label='j')
plt.legend(fontsize=15)
plt.xlabel('Time', fontsize= 30)
plt.xticks(fontsize= 20)
plt.ylabel('jx', fontsize= 30)
plt.yticks(fontsize= 20)
plt.show()

但似乎由于常量不是“标量”,代码不可解。

我也参考过这个帖子:Plotting solved ordinary differential equations over changing constant values 但方法和结果不是我想要的 我没有解决方案,不知道如何包含这个周期性变化的值并解决系统。

或者这种情况下 odeint 不可用?

提前感谢任何答案。

【问题讨论】:

    标签: python differential-equations


    【解决方案1】:

    从纯 Python 的角度来看,这个函数有几处错误

    def l(f):
        if int(2*t)%2np.pi == 0:
            return 1
        else:
            return -1
    
    • 函数中没有使用参数f,而是出现了一个未声明的t
    • 2np.pi 应该立即给出语法错误
    • int(2*t)%2*np.pi(int(2*t)%2)*np.pi,这可能不是我们想要的解释。使用int((2*f)%(2*np.pi))。您也可以取消 2
    • 较低的值是-1,而在描述中你有0

    • model 是一个包含 3 个状态组件的系统,您的初始状态有 5 个组件。那不兼容。

    • 应将重复表达式分配给局部变量以避免冗余计算。

    请报告详细的错误描述,而不仅仅是您对观察到的错误的总结。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多