[Tex/LaTex] How to do mathematical programming in LaTeX

pgfmath

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.

Best Answer

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)}]
    \addplot[black] gnuplot {!{f}};
  \end{axis} 
\end{tikzpicture}
\end{pysub}

\end{document}

enter image description here

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]
    \addplot[black] table {file.dat};
  \end{axis} 
\end{tikzpicture}
\end{center}

\end{document}

output2

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]
    \addplot[black] table {osciTV.dat};
    \addplot[dashed,variable=t,domain=0:!{tmax}] gnuplot {sin(!{omega_ext}*t)};   
  \end{axis} 
\end{tikzpicture}
\end{pysub}


\end{document}

See also the examples from the pythontex-gallery.

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.