SAGE : Making Slope Fields in Sage

Making slope fields in SageMath is relatively simple and requires only a few lines of code.  There are two different ways to add integral curves, or solutions.

1. Create a slope field for the differential equation: $y'=x-y^2$

Code

  1. First define two variables for $x$ and $y$.
  2. Store $f(x,y)$ into a variable, I choose yprime.
  3. Plot the slopefield defining the range for both $x$ and $y$, and store this into a "graphics" variable, p1. I also specified a color. This step is optional as $f(x,y)$ can be used in the plot_slope_field function. I also specified a color.
  4. Show the plot.

A much simpler input using only two lines of code is to define the $x$ and $y$ variables, and then create the slope field:

x,y = var('x y')
plot_slope_field(x-y^2,(x,0,6), (y,-3,3))

Change the above code to use only those two lines.


2. Now add some stream lines to show possible solutions.


3. Plot a slopefield and one solution curve

This method requires different code than above. It also uses a numerical method (Runge-Kutta) that we will cover a little later. These SageMath cells can be altered and reevaluated either by pressing the Evaluate button, or pressing shift+enter.

Code

  1. Create the independent variable $x$.
  2. Create the variable $y$ to be an actual function $y(x)$.
  3. Store $f(x,y)$ into a variable.
  4. The big command to numerically approximate a solution, and also give the slope field.