39

In earlier thread Jake provided some code whom successfully draws the following differential equations in the range [0; 1]

dy/dx=2*x
dy/dx=x*sqrt(x)

See: How to draw slope fields with all the possible solution curves in latex

I have not been able to determine how to change the range to [-1; 1] for both dimensions. My attempt

xmin=-1.1, xmax=1.1, % Axis limits
ymin=-1.1, ymax=1.1,
domain=-1:1, y domain=-1:1,

Also, I had some trouble with the notation for a differential equation that consists of y, example (dy/dx=x^2+y^2-1).

My attempt:

declare function={f(\x) = \x^2 + f(\x)^2 - 1;}
g.kov
  • 21,864
  • 1
  • 58
  • 95

4 Answers4

36

Using PGFPlotstable, you can use a naive numerical integration scheme to find the function directly within LaTeX:

\documentclass{article}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat=1.8}

\usepackage{amsmath}

\pgfplotstableset{
    create on use/x/.style={
        create col/expr={
            \pgfplotstablerow/201*2-1
        }
    },
    create on use/y/.style={
        create col/expr accum={
            \pgfmathaccuma+(2/201)*(abs(\pgfmathaccuma^2)+abs(\thisrow{x}^2)-1)
        }{0.6}
    }
}


\pgfplotstablenew{201}\loadedtable

\begin{document}
\begin{tikzpicture}
\begin{axis}[
    view={0}{90},
    domain=-1:1,
    y domain=-1:1,
    xmax=1, ymax=1,
    samples=21
]
\addplot3 [gray, quiver={u={1}, v={x^2+y^2-1}, scale arrows=0.075, every arrow/.append style={-latex}}] (x,y,0);
\addplot [thick, red] table [x=x, y=y] {\loadedtable};
\end{axis}
\end{tikzpicture}

\end{document} 
Jake
  • 232,450
31

(Sets of) ordinary differential equations (ODE) can be numerically solved using \pstODEsolve from the pst-ode Plain-TeX / LaTeX package.

Integration of the ODEs is done using the Runge-Kutta-Fehlberg method (RKF45).

Run 2 times lualatex or the sequence of commands

latex myfile
dvips myfile
ps2pdf -dNOSAFER myfile.ps

on the TeX input. Either method writes the result table into a text file on the first run. The first method makes use of luapstricks, a PostScript interpreter recently written by Marcel Krüger.

\documentclass{article}

\usepackage{pst-ode} \usepackage{amsmath} \usepackage{pgfplots} \pgfplotsset{compat=newest}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %solve dy/dx=x^2 + y^2 - 1 numerically for different initial values of y in the %interval x=[-1.1,1.1]; write resulting curves as tables with 100 output points %into text files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%y0=-0.5 --> y0=-0.5.dat \pstODEsolve[algebraicOutputFormat,algebraic,saveData]{% y0=-0.5% %name of the output file y0=-0.5.dat' }{ t | x[0] %table format iny0=-0.5.dat': x y }{ -1.1 %integration domain x_min=-1.1 }{ 1.1 %integration domain x_max=1.1 }{ 100 %number of output points }{ -0.5 %initial value y0(x_min) }{ t^2+x[0]^2-1 % right hand side of ODE, note the special notation: x --> t, y --> x[0] }

%y0=0.0 --> y0=0.0.dat \pstODEsolve[algebraicOutputFormat,algebraic,saveData]{y0=0.0}{t | x[0]}{-1.1}{1.1}{100}{0.0}{t^2+x[0]^2-1}

%y0=0.5 --> y0=0.5.dat \pstODEsolve[algebraicOutputFormat,algebraic,saveData]{y0=0.5}{t | x[0]}{-1.1}{1.1}{100}{0.5}{t^2+x[0]^2-1} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document} \IfFileExists{y0=-0.5.dat}{}{dummy text\end{document}}

\begin{tikzpicture} \begin{axis}[ axis equal image, % Unit vectors for both axes have the same length xmin=-1.1, xmax=1.1, % Axis limits ymin=-1.1, ymax=1.1, xtick={-1,-0.5,0,0.5,1}, ytick={-1,-0.5,0,0.5,1}, % Tick marks no markers, title={$\dfrac{\mathrm{d}y}{\mathrm{d}x}=x^2+y^2-1$}, view={0}{90},samples=21,domain=-1.1:1.1, y domain=-1.1:1.1, %for direction field ] \addplot3 [gray, quiver={u={1}, v={x^2+y^2-1}, scale arrows=0.075, every arrow/.append style={-latex}}] (x,y,0); \addplot table {y0=-0.5.dat}; \addplot table {y0=0.0.dat}; \addplot table {y0=0.5.dat}; \end{axis} \end{tikzpicture}

\end{document}

enter image description here

AlexG
  • 54,894
  • 1
    See my edit for running everything from within one file. Then you do not need the \if... structures –  Oct 17 '13 at 09:17
  • 1
    @Herbert: Thanks a lot. I assimilated your suggestion in the second code block. – AlexG Oct 17 '13 at 10:41
  • I don't get the three lines, I get the arrows to show, but not the lines. I get an error about not being able to read the tables. – MaoYiyi Oct 17 '13 at 13:03
  • @MaoYiyi: (1) Copy contents of 2nd code block into a file, say myfile.tex. (2) Run pdflatex --shell-escape myfile. (3) Open myfile.pdf in a PDF reader of your choice. Option --shell-escape is crucial here, as it allows for automatically executing the tex,dvips,ps2pdf chain for producing the data tables in the files y0=*.dat. – AlexG Oct 17 '13 at 13:14
29

enter image description here

MWE with Asymptote

% odeslope.tex:
%
\documentclass{article}
\usepackage[inline]{asymptote}
\usepackage{lmodern}
\begin{document}
\begin{figure}
\centering
\begin{asy}
import graph;
import slopefield;
import fontsize;
defaultpen(fontsize(9pt));
size(200);
real dy(real x,real y) {return x^2+y^2-1;}
real xmin=-1, xmax=1;
real ymin=-0.2, ymax=1;

add(slopefield(dy,(xmin,ymin),(xmax,ymax),20,deepgreen+0.4bp,Arrow));

pair C=(0.5,0.4);
draw(curve(C,dy,(xmin,ymin),(xmax,ymax)),deepblue+1bp);

label("$C$",C,NE,UnFill);
dot(C,UnFill);

xaxis(YEquals(ymin),xmin,xmax,LeftTicks());
xaxis(YEquals(ymax),xmin,xmax);
yaxis(XEquals(xmin),ymin,ymax,RightTicks());
yaxis(XEquals(xmax),ymin,ymax);
\end{asy}
\caption{$\frac{\mathrm{d}y}{\mathrm{d}x}=x^2+y^2-1$}
\end{figure}
\end{document}
%
% Process:
%
% pdflatex odeslope.tex
% asy odeslope-*.asy
% pdflatex odeslope.tex
g.kov
  • 21,864
  • 1
  • 58
  • 95
  • Does it use first order Euler method for integration? – AlexG Oct 16 '13 at 14:32
  • 1
    @AlexG: The documentation is humble about it, but the code in slopefield.asy looks more like the Runge–Kutta method. – g.kov Oct 16 '13 at 14:59
  • 1
    Yes and it seems to apply some automatic step size adaption. Thus, it is quite accurate. – AlexG Oct 16 '13 at 15:41
  • 1
    You only provide code and the code isn't TikZ. Can you provide some motivation and/or answer as to why this is relevant? –  Oct 17 '13 at 09:19
  • 7
    @Marc van Dongen: Please, not again. It was once concluded after long and painful discussion that TikZ/PSTriks/Metapost/Asymptote are somewhat equivalent and the community can only benefit from answers that provide alternative approaches to get the desired high quality graphics with TeX and friends. – g.kov Oct 17 '13 at 10:40
  • 3
    @MarcvanDongen: There was a bit of discussion about the relevance of Asymptote in the comments to http://tex.stackexchange.com/a/117436/2552, and the votes and lack of opposition on http://meta.tex.stackexchange.com/q/3518/2552 also seem to be quite a clear indicator that Asymptote can be considered equivalent to TikZ/PSTricks for the purposes of this site. I think the community has kind of come to the conclusion that questions about generating graphics can be answered with different tools (even if the question asks about a particular one) without having to list the pros and cons of the ... – Jake Oct 17 '13 at 10:55
  • 1
    ... (continued) chosen package. Almost every TikZ answer has a PSTricks answer simply starting with "With PSTricks, just for fun" or "Run with XeLaTeX", and vice versa. – Jake Oct 17 '13 at 10:56
  • @Jake: Not that Asymptote is off-site, but the OP clearly asks for a pgfplots solution. – AlexG Oct 17 '13 at 11:21
  • 4
    @AlexG: I know, but as I said, many questions get answers using different tools, even if the question asks for a particular one. The community has more or less agreed on this being a welcome thing (see http://meta.tex.stackexchange.com/questions/3408/downvoting-answers-exploiting-different-approaches-with-respect-to-the-initial-q): Even if the answers might not be relevant to the asker because they're bound to a particular tool, other people will definitely benefit from seeing a range of different approaches. – Jake Oct 17 '13 at 11:25
  • @Jake: Ok, agreed and thanks for clarifying this. – AlexG Oct 17 '13 at 11:30
  • 1
    @Marc van Dongen: new members don't have to be aware of the history, they just need an unbiased view of possible alternatives they can use. Also, this question is kind of an extension of the earlier thread, where the OP was looking for a simple method to use repetitively on different equations; without having to code each equation; to make/produce/draw the slope field of that equation. – g.kov Oct 17 '13 at 14:13
  • @g.kov How can we change the size of the arrows in you code? – Black Mild Nov 15 '21 at 02:27
  • @BlackMild Assume that you don't know yet, it is tickfactor. – Nguyen Van Chi Jan 07 '22 at 11:07
  • @NguyenVanChi1998 I checked, it is tickfactor! Thanks for pointing it out! – Black Mild Jan 07 '22 at 11:28
17

A PSTricks solution, it can be run with xelatex but that takes a lot of time in difference to latex->dvips->ps2pdf

\documentclass[border=10pt]{standalone}
\usepackage{pst-plot,pst-ode}
\begin{document}

\psset{unit=3}
\begin{pspicture}(-1.2,-1.2)(1.1,1.1)
\psaxes[ticksize=0 4pt,axesstyle=frame,tickstyle=inner,subticks=20,
        Ox=-1,Oy=-1](-1,-1)(1,1)
\psset{arrows=->,algebraic}
\psVectorfield[linecolor=black!60](-0.9,-0.9)(0.9,0.9){ x^2+y^2-1 }
%y0_a=-0.5
\pstODEsolve[algebraicOutputFormat]{y0_a}{t | x[0]}{-1}{1}{100}{-0.5}{t^2+x[0]^2-1}
%y0_b=0.0
\pstODEsolve[algebraicOutputFormat]{y0_b}{t | x[0]}{-1}{1}{100}{0.0}{t^2+x[0]^2-1}
%y0_c=0.5
\pstODEsolve[algebraicOutputFormat]{y0_c}{t | x[0]}{-1}{1}{100}{0.5}{t^2+x[0]^2-1}

\psset{arrows=-,linewidth=1pt}%
\listplot[linecolor=red  ]{y0_a}
\listplot[linecolor=green]{y0_b}
\listplot[linecolor=blue ]{y0_c}
\end{pspicture}

\end{document}

enter image description here