繁体   English   中英

使用 Python 求解非线性微分一阶方程

[英]Solving nonlinear differential first order equations using Python

我想使用 Python 求解非线性一阶微分方程。

例如,

df/dt = f**4

我写了下面的程序,但是matplotlib有问题,所以不知道我用scipy的方法对不对。

from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
derivate=lambda f,t: f**4
f0=10
t=np.linspace(0,2,100)
f_numeric=scipy.integrate.odeint(derivate,f0,t)
print(f_numeric)
plt.plot(t,f_numeric)
plt.show()

这导致以下错误:

AttributeError: 'float' object has no attribute 'rint'

在这种情况下,您最好使用Sympy ,它允许您获得封闭形式的解决方案:

from IPython.display import display
import sympy as sy
from sympy.solvers.ode import dsolve
import matplotlib.pyplot as plt
import numpy as np

sy.init_printing()  # LaTeX like pretty printing for IPython


t = sy.symbols("t", real=True)
f = sy.symbols("f", function=True)


eq1 = sy.Eq(f(t).diff(t), f(t)**4)  # the equation 
sls = dsolve(eq1)  # solvde ODE

# print solutions:
print("For ode")
display(eq1)
print("the solutions are:")
for s in sls:
    display(s)

# plot solutions:
x = np.linspace(0, 2, 100)
fg, axx = plt.subplots(2, 1)
axx[0].set_title("Real part of solution of $\\frac{d}{dt}f(t)= (f(t))^4$")
axx[1].set_title("Imag. part of solution of $\\frac{d}{dt}f(t)= (f(t))^4$")
fg.suptitle("$C_1=0.1$")
for i, s in enumerate(sls, start=1):
    fn1 = s.rhs.subs("C1", .1)  # C_1 -> 1
    fn2 = sy.lambdify(t, fn1, modules="numpy")  # make numpy function
    y = fn2(x+0j)  # needs to be called with complex number
    axx[0].plot(x, np.real(y), label="Sol. %d" % i)
    axx[1].plot(x, np.imag(y), label="Sol. %d" % i)
for ax in axx:
    ax.legend(loc="best")
    ax.grid(True)
axx[0].set_ylabel("Re$\\{f(t)\\}$")
axx[1].set_ylabel("Im$\\{f(t)\\}$")
axx[-1].set_xlabel("$t$")
fg.canvas.draw()
plt.show()

在 IPython shell 中,您应该看到以下内容:

解决方案

阴谋

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM