我在计算逻辑微分方程:
y' = ky(L-y)
计算工作。唯一不起作用的是我不能用matplotlib.pyplot或sympy.plot绘制它
我认为问题是如何定义f
的ft
变量。
这是MWE:
# https://natelemoine.com/using-sympy-for-biological-odes/
import sympy as sm
import numpy as np
import matplotlib.pyplot as plt
from sympy.abc import L, k, t
y = sm.Function('y')(t)
# The differential equation: y' = ky(L-y)
# Define the derivative of y with respect to t (the left-hand side of the ODE),
# and then define the right-hand side of the ODE.
dy = y.diff(t)
rhs = k*y*(L - y)
# Define the equality
eq = sm.Eq(dy, rhs)
print('the Differential equation is:')
sm.pretty_print(eq)
print('the Differential equation solution is:')
sol = sm.dsolve(eq)
sm.pretty_print(sol)
print('the solution of the Differential equation for initial value of y(0) = 800:')
t0 = sol.args[1].subs({'t': 0})
n0 = 800
eq_init = sm.Eq(n0, t0)
C1 = t0.args[2].args[0].args[0]
t0_sol = sm.solve(eq_init, C1)
# substitute the expression for C1 back into the equation
final = sol.args[1].subs(C1, t0_sol[0])
final_eq = final.simplify()
sm.pretty_print(final_eq.subs([(L,2000),(k,0.0003)]))
f = final_eq.subs([(L,2000),(k,0.0003)])
ft = np.linspace(0, 10, 1)
plt.plot(f, ft)
plt.show()
1条答案
按热度按时间wsxa1bj11#
我想你想把
f
画成时间的函数。问题是这样的:plt.plot
需要两个参数,x坐标列表和y坐标列表。显然,您提供了一个符号表达式作为第一个参数,而matplotlib不知道它是什么。解决方案。绘制符号表达式的最简单方法是使用symony的绘图功能或SymPy Plotting Backends module:
如果你想直接使用matplotlib,你必须将符号表达式转换为数值函数并对其求值。举例来说: