Represent a first order differential equation in numpy

心不动则不痛 提交于 2019-12-22 18:42:39

问题


I have an equation dy/dx = x + y/5 and an initial value, y(0) = -3.

I would like to know how to plot the exact graph of this function using pyplot.

I also have a x = np.linspace(0, interval, steps+1) which I would like to use as the x axis. So I'm only looking for the y axis values.

Thanks in advance.


回答1:


Just for completeness, this kind of equation can easily be integrated numerically, using scipy.integrate.odeint.

import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

# function dy/dx = x + y/5.
func = lambda y,x : x + y/5.
# Initial condition
y0 = -3  # at x=0
# values at which to compute the solution (needs to start at x=0)
x = np.linspace(0, 4, 101)
# solution
y = odeint(func, y0, x)
# plot the solution, note that y is a column vector
plt.plot(x, y[:,0])
plt.xlabel('x')
plt.ylabel('y')
plt.show()




回答2:


Given that you need to solve the d.e. you might prefer doing this algebraically, with sympy. (Or you might not.)

Import the module and define the function and the dependent variable.

>>> from sympy import *
>>> f = Function('f')
>>> var('x')
x

Invoke the solver. Note that all terms of the d.e. must be transposed to the left of the equals sign, and that the y must be replaced by the designator for the function.

>>> dsolve(Derivative(f(x),x)-x-f(x)/5)
Eq(f(x), (C1 + 5*(-x - 5)*exp(-x/5))*exp(x/5))

As you would expect, the solution is given in terms of an arbitrary constant. We must solve for that using the initial value. We define it as a sympy variable.

>>> var('C1')
C1

Now we create an expression to represent this arbitrary constant as the left side of an equation that we can solve. We replace f(0) with its value in the initial condition. Then we substitute the value of x in that condition to get an equation in C1.

>>> expr = -3 - ( (C1 + 5*(-x - 5)*exp(-x/5))*exp(x/5) )
>>> expr.subs(x,0)
-C1 + 22

In other words, C1 = 22. Finally, we can use this value to obtain the particular solution of the differential equation.

>>> ((C1 + 5*(-x - 5)*exp(-x/5))*exp(x/5)).subs(C1,22)
((-5*x - 25)*exp(-x/5) + 22)*exp(x/5)

Because I'm absentminded and ever fearful of making egregious mistakes I check that this function satisfies the initial condition.

>>> (((-5*x - 25)*exp(-x/5) + 22)*exp(x/5)).subs(x,0)
-3

(Usually things are incorrect only when I forget to check them. Such is life.)

And I can plot this in sympy too.

>>> plot(((-5*x - 25)*exp(-x/5) + 22)*exp(x/5),(x,-1,5))
<sympy.plotting.plot.Plot object at 0x0000000008C2F780>



来源:https://stackoverflow.com/questions/42629634/represent-a-first-order-differential-equation-in-numpy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!