numpy 从Sympy中绘制Logistic微分方程解

eanckbw9  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(64)

我在计算逻辑微分方程:

y' = ky(L-y)

计算工作。唯一不起作用的是我不能用matplotlib.pyplot或sympy.plot绘制它
我认为问题是如何定义fft变量。
这是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()
wsxa1bj1

wsxa1bj11#

我想你想把f画成时间的函数。问题是这样的:

plt.plot(f, ft)

plt.plot需要两个参数,x坐标列表和y坐标列表。显然,您提供了一个符号表达式作为第一个参数,而matplotlib不知道它是什么。
解决方案。绘制符号表达式的最简单方法是使用symony的绘图功能或SymPy Plotting Backends module

sm.plot(final_eq.subs([(L,2000),(k,0.0003)]), (t, 0, 10))

如果你想直接使用matplotlib,你必须将符号表达式转换为数值函数并对其求值。举例来说:

f_num = sm.lambdify([k, L, t], final_eq)
t_coords = np.linspace(0, 10, 100)
y_coords = f_num(0.0003, 2000, t_coords)

plt.figure()
plt.plot(t_coords, y_coords)
plt.xlabel("x [s]")
plt.ylabel("f(t)")

相关问题