鱼C论坛

 找回密码
 立即注册
查看: 3902|回复: 2

[已解决]求解使用python与matlab解二阶非线性微分方程组

[复制链接]
发表于 2023-9-23 22:53:49 | 显示全部楼层    本楼为最佳答案   
对于这个问题,我们可以使用Python的SciPy库中的odeint函数来解决。首先,需要将二阶微分方程组转化为一阶微分方程组。我们可以定义状态向量x和时间t,其中x包括x,x_dot,theta,和theta_dot。然后,我们可以定义一个函数来计算状态向量的导数。最后,使用odeint函数来解决微分方程组。

以下是使用Python解决二阶非线性微分方程组的代码:

  1. import numpy as np
  2. from scipy.integrate import odeint

  3. m1 = 1.0
  4. m = 2.0
  5. l = 1.0
  6. g = 10
  7. F = 1.0
  8. Dx = 0.1
  9. Dtheta = 0.1

  10. def derivs(x, t):
  11.     x_dot = x[1]
  12.     theta = x[2]
  13.     theta_dot = x[3]
  14.    
  15.     c = np.cos(theta)
  16.     s = np.sin(theta)
  17.    
  18.     x_ddot = (F - Dx*x_dot + m*l*theta_dot*s - m*l*theta_ddot*c) / (m + m1)
  19.     theta_ddot = (m*g*l*s - Dtheta*theta_dot - m*l*x_dot*c) / (4/3*m*(l**2))
  20.    
  21.     return [x_dot, x_ddot, theta_dot, theta_ddot]

  22. # 初始设置
  23. x0 = [0.0, 0.0, 0.1, 0.0]  # x, x_dot, theta, theta_dot
  24. t = np.linspace(0, 10, 1000)

  25. # 解决微分方程组
  26. x = odeint(derivs, x0, t)

  27. # 绘制结果
  28. import matplotlib.pyplot as plt
  29. plt.plot(t, x[:, 0], label='x')
  30. plt.plot(t, x[:, 2], label='theta')
  31. plt.legend()
  32. plt.show()
复制代码


对于Matlab,我们可以使用ode45函数来解决微分方程组。以下是使用Matlab解决二阶非线性微分方程组的代码:

  1. m1 = 1.0;
  2. m = 2.0;
  3. l = 1.0;
  4. g = 10;
  5. F = 1.0;
  6. Dx = 0.1;
  7. Dtheta = 0.1;

  8. function x_dot = derivs(t, x)
  9.     x_dot = zeros(4, 1);
  10.     x_dot(1) = x(2);
  11.     theta = x(3);
  12.     theta_dot = x(4);
  13.    
  14.     c = cos(theta);
  15.     s = sin(theta);
  16.    
  17.     x_ddot = (F - Dx*x(2) + m*l*theta_dot*s - m*l*theta_ddot*c) / (m + m1);
  18.     theta_ddot = (m*g*l*s - Dtheta*theta_dot - m*l*x(2)*c) / (4/3*m*(l^2));
  19.    
  20.     x_dot(2) = x_ddot;
  21.     x_dot(3) = theta_dot;
  22.     x_dot(4) = theta_ddot;
  23. end

  24. % 初始设置
  25. x0 = [0.0, 0.0, 0.1, 0.0];  % x, x_dot, theta, theta_dot
  26. tspan = [0, 10];

  27. % 解决微分方程组
  28. [t, x] = ode45(@derivs, tspan, x0);

  29. % 绘制结果
  30. plot(t, x(:, 1), 'r', t, x(:, 3), 'b');
  31. legend('x', 'theta');
复制代码


这两个代码都可以解决这个问题,但是Matlab的代码可能会更快一些,因为它使用了更高效的ode45函数。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-9-22 11:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表