简体   繁体   中英

Solving nonlinear differential first order equations using Python

I would like to solve a nonlinear first order differential equation using Python.

For instance,

df/dt = f**4

I wrote the following program, but I have an issue with matplotlib, so I don't know if the method I used with scipy is correct.

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()

Which results in the following error:

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

In this case, you might be better of using Sympy , which allows you to obtain the closed form solutions:

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()

In an IPython shell, you should see the following:

解决方案

阴谋

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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