Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

python - Problems with the example of solve_ivp [scipy.integrate]

I am studying python for what concerns ode numerical integration, in particular I found the scipy.integrate function solve_ipv . I tried the example shown in the scipy.integrate.solve_ipv page but there is a clear mistake in the code related to the Lotka Volterra example:

def lotkavolterra(t, z, a, b, c, d):
    x, y = z
    return [a*x - b*x*y, -c*y + d*x*y]

sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1))

t = np.linspace(0, 15, 300)
z = sol.sol(t)

import matplotlib.pyplot as plt
plt.plot(t, z.T)
plt.xlabel('t')
plt.legend(['x', 'y'], shadow=True)
plt.title('Lotka-Volterra System')
plt.show()
  1. sol.sol(t) has no meaning in this code. What should we write? Maybe a tuple z = sol.t, sol.y ?

  2. It is also clear that len(sol.y[0])=57 and len(sol.y[1])=57 while t has 300 elements. For this reason coupling their values for a plot can be a problem.

In the page there is also a plot of what we would obtain if the code run.

I don't think it's important but I am using python3.

EDIT: I did not insert dense_output=True in solv_ipv()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the solver call

sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
                dense_output=True)

the last option dense_output=True is responsible for adding the sol function to the solution "bunch" object. This function implements the method-specific piecewise polynomial interpolation that in the literature is called "dense output". Thus the next two lines make complete sense, as z = sol.sol(t) contains a sample for any point in t.

This option does not change the sequence of internal nodes and step sizes. sol.t and sol.y contain the same values with or without that option. There is even no additional computation involved, as the stepper computes this interpolation polynomial for every step. This is used even without the dense output option in the event mechanism. Only the memory use is increased when the individual interpolation polynomials are stored after each step and assembled in the dense output function.


To avoid the confusion of sol.sol, some have taken res for "result" or similar as the variable name for the solver return value, so that the interpolation function is accessed as res.sol(t).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...