3

(Python newbie here) As a learning exercise I am trying to solve and plot the solution to a very simple ODE: dy/dt = y with y(0) = 1. I believe my code to solve the ODE is correct, but the x-axis limits of the plot are very strange. I made 50 equally spaced x-values ranging from 0 to 5, but it looks as if plt.plot() is plotting only the first two points, resulting in the graph looking like a line rather than the curve y = e^x. I tried playing around with the 'scalex' and 'scaley' arguments of plt.plot(), and I also tried plt.xlim = (0,5), and variations thereof, but to no avail. My code is below (I'm using Python 3.7.6):

import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
def f(t,y):
 return(y)
t0 = np.linspace(0,5,50)
y0 = np.array([1])
#solve_ivp(fun, t_span, y0, args = None)
out = solve_ivp(f, t0, y0)
t_vals = out.t
y_vals = out.y[0,:]
plt.plot(t_vals,y_vals)

Here's the plot I'm getting:

I did try setting y = np.exp(t0) and then plotting t0 vs y0, which works perfectly (i.e. with the x values ranging from 0 to 5). So I'm not sure why my original code is not giving me the same type of graph. Perhaps my attempt to subset the variable out is somehow incorrect? ...Any help would be appreciated!

asked Jul 12, 2020 at 18:35

1 Answer 1

1

By looking at the documentation for solve_ivp, you can see that t_span should be a 2-tuple of floats, and you can specify the step with max_step

So you can have:

from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
def f(t,y):
 return(y)
out = solve_ivp(f, (0, 5), [1], max_step=0.1)
t_vals = out.t
y_vals = out.y[0,:]
plt.plot(t_vals,y_vals)

Which gives you the expected graph: enter image description here

answered Jul 12, 2020 at 19:09
1
  • Thank you! I didn't read the documentation carefully enough :) Commented Jul 12, 2020 at 20:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.