gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:15:47 25 4
gpt4 key购买 nike

我想使用 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 中,您应该看到以下内容:

Solutions

Plot

关于python - 使用 Python 求解非线性微分一阶方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30687786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com