You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组代入SymPy求解的方程并实现绘图?

解决方法

要把SymPy求解得到的符号解应用到数值数组并绘图,核心是把符号表达式转换为可计算的数值函数,具体步骤如下:

1. 提取符号解表达式

dsolve返回的是方程形式的结果,先提取出x(t)的具体表达式:

x_sol = result.rhs  # 获取方程右侧的解表达式

2. 转换为支持NumPy数组的函数

使用SymPy的lambdify工具,将符号函数转换成能处理数值数组的函数:

x_func = sy.lambdify(t, x_sol, 'numpy')

这里'numpy'参数指定用NumPy的运算逻辑,确保对数组的支持。

3. 计算数值并绘图

导入Matplotlib,计算x_val对应的函数值,然后绘制图像:

import matplotlib.pyplot as plt

y_val = x_func(x_val)
plt.plot(x_val, y_val)
plt.xlabel('t')
plt.ylabel('x(t)')
plt.title('微分方程 x''(t) - x(t) = cos(t) 的解')
plt.grid(True)
plt.show()

完整可运行代码

import sympy as sy
import numpy as np
import matplotlib.pyplot as plt

t,m,k,c  = sy.symbols('t m k c')
x = sy.Function('x')

diffeq = sy.Eq(x(t).diff(t, t) - x(t), sy.cos(t)) 
result = sy.dsolve(diffeq, ics={x(0): 0, sy.diff(x(t), t).subs(t,0): 0})

# 提取解并转换为数值函数
x_sol = result.rhs
x_func = sy.lambdify(t, x_sol, 'numpy')

# 生成自变量数组并计算函数值
x_val = np.linspace(0,10,100)
y_val = x_func(x_val)

# 绘制图像
plt.plot(x_val, y_val)
plt.xlabel('t')
plt.ylabel('x(t)')
plt.title('微分方程 x''(t) - x(t) = cos(t) 的解')
plt.grid(True)
plt.show()

内容的提问来源于stack exchange,提问作者KitingPaul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:45:43