Sunday, 21 September 2014

Generate slope fields in R and Python

Here is a short post on how to generate a quick slope field in R and Python.

If you do not know what a slope field is, well I am not the best person to explain it to you since it is a relative new concept for me as well. From what I’ve understood on the subject, a slope field is a graphical way to sort out a first-order differential equation and get a grasp at the solution without having to solve it analytically.

As the Wikipedia’s page says, “it may be used to qualitatively visualize solutions, or to numerically approximate them.”

In general, I feel safe saying that a slope field is some sort of a graphical approach to a differential equation.

Say you have the following differential equation:

clip_image002[8]

drawing the slope field would look something like this:
In Python (without arrows)
figure_1_3figure_2_1

and in R (with arrows, x=f and y=h)
Rplot

Of course these plots are just very quick and can be improved.

Here is the Python code I used to draw them.


And the R code


Here is a beautiful slope field for the following differential equation:

clip_image002[10]

In Python
x y


If you need a quick tool for drawing slope fields, this online resource is good, click here.


Hope this was interesting.

5 comments:

  1. I think it should be "return y/x" for diff definition .

    ReplyDelete
    Replies
    1. Hi Kim! Thanks for spotting and reporting the mistake! Fixed!

      Delete
    2. It should be corrected for "R" program also.

      Delete
  2. Is there a built in function in python that one can import from a module that gives us the slope field?

    ReplyDelete
  3. Thanks for the article. Very helpfull. Obrigado

    ReplyDelete