# How to do mathematical programming in LaTeX?

I typically write my programs in Matlab and then port the picture into LaTeX. At times it appears that one has better efficiency or flexibility to have the program within LaTeX itself, either you have access to more control over graphing or that the work-flow is easier. I am looking for an intermediate article that explains elements of mathematical programming in LaTeX. Typical math programs are items such as Newton method for root finding, Runge-Kutta solution of differential equations, basic Monte Carlo, etc. If no such article exists links to your sample math-within-LaTeX would be appreciated.

Edit 4/3/2019

Where Matlab does not function well is in "annotations". Matlab performs nicely so long as you are plotting some graph. But if you are putting pieces together and adding text, arrows, etc to a plot then it becomes a bit of problem to use Matlab. Matlab has an "annotation" function to help you do this but it is geared to "normalized windows coordinates", which somehow takes your window to be $[0,1]*[0,1]$ and asks you specify the coordinates with respect to this window, as opposed to your data coordinates. This is perhaps for interactive placement of annotations on the graph but it is awkward to use for data-driven annotations. The switch-over is confusing enough to have created a side industry of third party contributed functions, most of which do not work because of one issue or another. Even if you manage to make it work then the annotations move around under zoom, as they are geared to the window you see not the data coordinates. In addition you encounter the limited version of \LaTeX that is supported by Matlab, for example here is the text support. In short, if you are contemplating a good bit of "hand modifications" to a graph then you may want to do it from start in \LaTeX. For drawing arrows in Matlab, "arrow3.m" functioned well.

• "do your math somewhere else, bring in your results for typesetting" – percusse Oct 20 '17 at 17:17
• If you're free to switch to Lua(La)TeX, you have instant access to Lua's library of math functions. – Mico Oct 20 '17 at 17:19
• For solving non-stiff ODEs with high accuracy (RKF45 with automatic step size) look at PSTricks pst-ode package. Example: Phase Plane Plot using pst-ode – AlexG Oct 21 '17 at 9:38
• PSTricks with its additional packages is quite a powerful tool. Manuel Luque's blog has many impressive examples, e. g.: pstricks.blogspot.de/search?q=oscillateur – AlexG Oct 21 '17 at 9:50
• You can use R code in a Latex file using swerve or knitr – Barranka Oct 21 '17 at 15:04

You can integrate python code into your LaTeX document using pythontex.

Here is a simple example:

\documentclass{article}

\usepackage[gobble=auto]{pythontex}
\usepackage{pgfplots}

\begin{document}

\begin{pycode}
from sympy import *
x = symbols('x')
f = integrate(cos(x)*sin(x), x)
\end{pycode}

\begin{pysub}
\begin{tikzpicture}
\begin{axis}[xlabel=$x$,ylabel=$y$,samples=200,no markers,title=!{latex(f)}]
\end{axis}
\end{tikzpicture}
\end{pysub}

\end{document}


Here is another example:

\documentclass{article}

\usepackage[gobble=auto]{pythontex}
\usepackage{pgfplots}
\usepackage{siunitx}

\sisetup{
round-mode=places,
round-precision=3
}

\DeclareDocumentCommand{\pyNum}{ m O{}}
{%
\py{'\\num[#2]{' + str(#1).replace('(','').replace(')','') + r'}'}%
}

\begin{document}

\begin{pycode}
import numpy as np
from scipy import optimize as op
def f(x):
return x**2 + 3*x  -3
x = np.arange(-5,5,0.1)
np.savetxt('file.dat',zip(x,f(x)),fmt='%0.5f')
\end{pycode}

A root of $f$ is \pyNum{op.newton(f,-2)}.

\begin{center}
\begin{tikzpicture}
\begin{axis}[xlabel=$x$,ylabel=$y$,samples=200,no markers,axis lines=center]
\end{axis}
\end{tikzpicture}
\end{center}

\end{document}


Here is a further example solving an ODE for a driven oscillator:

\documentclass{article}

\usepackage[gobble=auto]{pythontex}
\usepackage{pgfplots}

\pgfplotsset{compat=1.15}

\begin{document}

\begin{pycode}
import numpy as np
from scipy.integrate import odeint

omega = 3

omega_ext = 2
c = 0.1
d = 0.5
m = 1
e = 1
k = omega**2*m

def Force(t,x,v):
return -k*x + np.sin(omega_ext*t) - d*v

def dgl(xv, t):
x, v = xv
return [v, 1/m*Force(t,x,v)]

xv0 = [1, 0]

tmax = 30
t_out = np.arange(0, tmax, 0.05)

xv_res = odeint(dgl, xv0, t_out)

x,v = xv_res.T

tv = list(zip(t_out,v))
np.savetxt('osciTV.dat',tv)
\end{pycode}

\begin{pysub}
\begin{tikzpicture}
\begin{axis}[xlabel=$t$,ylabel=$v$,samples=200,no markers]
\end{axis}
\end{tikzpicture}
\end{pysub}

\end{document}


Python provides many libraries for scientific computing.

Another option would to use sagetex which let's you include sage-code into your document.

Note that it makes sense to think about choosing an editor which supports switching between two languages in one document. Emacs can do this for example with polymode.

• I think it would be useful to mention, perhaps at the start, that despite the name of the package, pythontex can be used with other languages. The languages listed in the manual (chapter 7) is Ruby, Julia, Octave, bash and Rust. – Torbjørn T. Oct 21 '17 at 9:20
• What language would you recommend researchers to use, especially for a new student? I know it doesn't really matter, but in case one needs to exchange code, using the same language is an advantage. The fact that despite of supporting other languages, the package name is python specifically suggest that Python is the best? – Ooker Oct 21 '17 at 18:59
• I would choose python because the basic syntax is easy to learn and use and there are many scientific libraries for it. As an alternative (and perhaps in the future) I would choose julia because of better performance. – student Oct 21 '17 at 19:47
• @Ooker, I would say that julia syntax is as easy to read as python. The aim whan developing julia was to create a language which is easy to read and learn as python but performs like C or fortran. I am not an expert in this, but for my purposes python has more and more mature libraries and emacs support seems to be better. However julia might be in the future the better option. That's my opinion, but I am not an expert and it might help you more to ask one, for example on stackexchange.com or stackoverflow.com. – student Oct 24 '17 at 10:43
• – student Oct 24 '17 at 10:45

For LuaLaTeX, and using Lua, but other than that:

pweave was mentioned in the answer by jonaslb, so it would make sense to also mention sweave (which was the inspiration for pweave) and knitr. These are frameworks for similar concepts, but for the R language.

MetaPost is also integrated in LuaTeX. As a programming language it allows the implementation of some numerical methods. See this tutorial for an implementation of the Newton iterative method (p. 34).

As a graphic language it also allows some geometric computations, like finding the intersection of two curves, building a box plot out of a stats diagram, etc.

Edit: as an example, here is a slightly modified implementation of the Newton method I mentioned above, applied to the function f(x)=x^2-2. It is a geometric version of this method, that is to say that it is based upon the given curve and its tangents, not upon the function itself and its derivative. (It could have been done that way, of course.)

\documentclass{scrartcl}
\usepackage{luamplib}
\mplibtextextlabel{enable}
\mplibsetformat{metafun}
\mplibnumbersystem{double}
\begin{document}
\begin{mplibcode}
vardef f(expr x) = x**2 - 2 enddef;
u = 3cm; v = 1.5cm;  xmax = 2.75; ymax = 6;
path curve; numeric t[]; dx = 1E-4;
curve = (0, f(0))
for i = dx step dx until xmax: .. (i, f(i)) endfor;
beginfig(1);
draw curve xyscaled (u, v);
x0 = 2.5; i := 0;
forever:
(t[i],whatever) = curve intersectiontimes
((x[i], -infinity) -- (x[i],infinity));
y[i] = ypart (point t[i] of curve);
(x[i+1],0) = z[i] + whatever*direction t[i] of curve;
draw ((x[i], 0) -- z[i] -- (x[i+1], 0)) xyscaled (u, v);
drawdot (z[i] xyscaled (u, v)) withpen pencircle scaled 4bp;
i := i+1;
exitif abs(x[i]-x[i-1]) < dx;
endfor;
label.bot(btex $x_0$ etex, (x0*u, 0));
label.bot(btex $x_1$ etex, (x1*u, 0));
label.bot(btex $x_2$ etex, (x2*u, 0));
label.lrt("$x_{" & decimal i & "}=" & decimal x[i] & "$",
(x[i]*u, 0) shifted (0, -.75cm));
drawarrow origin -- (xmax*u, 0);
for i = 0 upto xmax:
draw (i*u, -2bp) -- (i*u, 2bp);
label.bot("$" & decimal i & "$", (i*u, -2bp));
endfor;
label.bot("$x$", (xmax*u, 0));
endfig;
\end{mplibcode}
\end{document}


Along the lines of percusse's comment, the sagetex package allows you to access to a computer algebra system, called Sage, which has math programming built in as well as Python. Searching for sagetex on this site will get you some quick examples. For example, if you want to plot the Riemann zeta function you can use the fact that Sage knows the Reimann zeta function and then you can print it out with tikz/pgfplots as is done in my answer here. Not having to program the zeta function saves you from having to waste time "reinventing the wheel". If the function isn't defined, such as the Cantor function, then it can be programmed in Python with the output nicely typeset in tikz/pgfplots as I showed in my answer here. Whether your math requires permutations, graph theory, statistics, matrices, randomly generated polynomial problems, blurring an image, or the various topics mentioned in the substantial documentation here, Sage plus Python is built to handle math. You can find documentation on Runge-Kutta here with Monte Carlo and various root finding methods. Your intermediate document is the sagetex link above to get you started and the sagemath links. Some basics of Python are discussed here.

The Sage CAS is not part of a LaTeX distribution. It can be download and installed locally on your machine or, if you have an internet connection, you can access it through the free CoCalc.

What I usually do when I want to typeset something based on results of some programming, is to include jinja-generated latex code. It's particularly great for tables, I think. There are some tips on how to do that here.

Another method, that I have not tried, but which looks extremely promising, is pweave, which lets you write Python code inside your latex document!

And as some of the other answers here write, you can use Lua with LuaLatex. Lua is a little more obscure though, so if you have to learn the language and is coming from Matlab, Python should be easier.