How to do mathematical programming in LaTeX? The Next CEO of Stack OverflowIs there a way to automatically transpose a matrix written in Latex?Plotting the Cantor functionHow do you plot the Riemann Zeta function using Tikz/Pgfplot?Partial or entire Image Blurring in TikZ?Can I draw my graphs (graph theory) with TikZ online?Phase Plane Plot using pst-odeGCD and PolynomialsRandom Permutations of List ItemsCalculating descriptive statisticsHow to omit printing the decimal part in pgfmath macrosHow to solve the 10.09999 rounding problem with pgfmath?Programming with pgf arrays : how to create an array?Using mathematical function in PGF/TikZErf function in LaTeXHow do you use division in LaTeX to adjust parameters?Programming Conway's Game of Life in LaTeXHow to define pgfmath local variables?Programming a step function- part2latex pgfmath precision

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

Can this note be analyzed as a non-chord tone?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

What is the process for cleansing a very negative action

What CSS properties can the br tag have?

Is there a way to save my career from absolute disaster?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Is it ever safe to open a suspicious HTML file (e.g. email attachment)?

Is there a difference between "Fahrstuhl" and "Aufzug"?

(How) Could a medieval fantasy world survive a magic-induced "nuclear winter"?

Can Sneak Attack be used when hitting with an improvised weapon?

Strange use of "whether ... than ..." in official text

What day is it again?

Is it correct to say moon starry nights?

My ex-girlfriend uses my Apple ID to login to her iPad, do I have to give her my Apple ID password to reset it?

what's the use of '% to gdp' type of variables?

Could a dragon use its wings to swim?

Defamation due to breach of confidentiality

TikZ: How to fill area with a special pattern?

Players Circumventing the limitations of Wish

Does destroying a Lich's phylactery destroy the soul within it?

Which one is the true statement?

Graph of the history of databases

Man transported from Alternate World into ours by a Neutrino Detector



How to do mathematical programming in LaTeX?



The Next CEO of Stack OverflowIs there a way to automatically transpose a matrix written in Latex?Plotting the Cantor functionHow do you plot the Riemann Zeta function using Tikz/Pgfplot?Partial or entire Image Blurring in TikZ?Can I draw my graphs (graph theory) with TikZ online?Phase Plane Plot using pst-odeGCD and PolynomialsRandom Permutations of List ItemsCalculating descriptive statisticsHow to omit printing the decimal part in pgfmath macrosHow to solve the 10.09999 rounding problem with pgfmath?Programming with pgf arrays : how to create an array?Using mathematical function in PGF/TikZErf function in LaTeXHow do you use division in LaTeX to adjust parameters?Programming Conway's Game of Life in LaTeXHow to define pgfmath local variables?Programming a step function- part2latex pgfmath precision










34















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.



Where Matlab fails is in "annotation". It is good 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 a "annotation" function to help you do this but it is geared to "normalized windows coordinate", 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. 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.










share|improve this question



















  • 44





    "do your math somewhere else, bring in your results for typesetting"

    – percusse
    Oct 20 '17 at 17:17






  • 4





    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






  • 2





    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







  • 2





    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







  • 3





    You can use R code in a Latex file using swerve or knitr

    – Barranka
    Oct 21 '17 at 15:04















34















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.



Where Matlab fails is in "annotation". It is good 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 a "annotation" function to help you do this but it is geared to "normalized windows coordinate", 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. 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.










share|improve this question



















  • 44





    "do your math somewhere else, bring in your results for typesetting"

    – percusse
    Oct 20 '17 at 17:17






  • 4





    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






  • 2





    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







  • 2





    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







  • 3





    You can use R code in a Latex file using swerve or knitr

    – Barranka
    Oct 21 '17 at 15:04













34












34








34


26






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.



Where Matlab fails is in "annotation". It is good 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 a "annotation" function to help you do this but it is geared to "normalized windows coordinate", 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. 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.










share|improve this question
















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.



Where Matlab fails is in "annotation". It is good 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 a "annotation" function to help you do this but it is geared to "normalized windows coordinate", 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. 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.







pgfmath






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 18 mins ago







Maesumi

















asked Oct 20 '17 at 17:13









MaesumiMaesumi

3,35343352




3,35343352







  • 44





    "do your math somewhere else, bring in your results for typesetting"

    – percusse
    Oct 20 '17 at 17:17






  • 4





    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






  • 2





    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







  • 2





    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







  • 3





    You can use R code in a Latex file using swerve or knitr

    – Barranka
    Oct 21 '17 at 15:04












  • 44





    "do your math somewhere else, bring in your results for typesetting"

    – percusse
    Oct 20 '17 at 17:17






  • 4





    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






  • 2





    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







  • 2





    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







  • 3





    You can use R code in a Latex file using swerve or knitr

    – Barranka
    Oct 21 '17 at 15:04







44




44





"do your math somewhere else, bring in your results for typesetting"

– percusse
Oct 20 '17 at 17:17





"do your math somewhere else, bring in your results for typesetting"

– percusse
Oct 20 '17 at 17:17




4




4





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





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




2




2





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






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





2




2





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






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





3




3





You can use R code in a Latex file using swerve or knitr

– Barranka
Oct 21 '17 at 15:04





You can use R code in a Latex file using swerve or knitr

– Barranka
Oct 21 '17 at 15:04










5 Answers
5






active

oldest

votes


















51














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



Here is a simple example:



documentclassarticle

usepackage[gobble=auto]pythontex
usepackagepgfplots

begindocument

beginpycode
from sympy import *
x = symbols('x')
f = integrate(cos(x)*sin(x), x)
endpycode


beginpysub
begintikzpicture
beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,title=!latex(f)]
addplot[black] gnuplot !f;
endaxis
endtikzpicture
endpysub

enddocument


enter image description here



Here is another example:



documentclassarticle

usepackage[gobble=auto]pythontex
usepackagepgfplots
usepackagesiunitx

sisetup
round-mode=places,
round-precision=3


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



begindocument

beginpycode
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')
endpycode

A root of $f$ is pyNumop.newton(f,-2).


begincenter
begintikzpicture
beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,axis lines=center]
addplot[black] table file.dat;
endaxis
endtikzpicture
endcenter

enddocument


output2



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



documentclassarticle

usepackage[gobble=auto]pythontex
usepackagepgfplots

pgfplotssetcompat=1.15

begindocument

beginpycode
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)
endpycode


beginpysub
begintikzpicture
beginaxis[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);
endaxis
endtikzpicture
endpysub


enddocument


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.






share|improve this answer




















  • 7





    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






  • 1





    @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






  • 1





    @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

    – student
    Oct 24 '17 at 10:45


















21














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



  • "Numerical methods with LuaLaTeX", by Juan Montijano, Mario Pérez, Luis Rández and Juan Luis Varona. TUGboat issue 35.1: https://www.tug.org/TUGboat/tb35-1/tb109montijano.pdf


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.






share|improve this answer
































    12














    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.)



    documentclassscrartcl
    usepackageluamplib
    mplibtextextlabelenable
    mplibsetformatmetafun
    mplibnumbersystemdouble
    begindocument
    beginmplibcode
    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;
    endmplibcode
    enddocument


    enter image description here






    share|improve this answer
































      6














      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.






      share|improve this answer






























        5














        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.






        share|improve this answer























          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "85"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f397234%2fhow-to-do-mathematical-programming-in-latex%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          5 Answers
          5






          active

          oldest

          votes








          5 Answers
          5






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          51














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



          Here is a simple example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          begindocument

          beginpycode
          from sympy import *
          x = symbols('x')
          f = integrate(cos(x)*sin(x), x)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,title=!latex(f)]
          addplot[black] gnuplot !f;
          endaxis
          endtikzpicture
          endpysub

          enddocument


          enter image description here



          Here is another example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots
          usepackagesiunitx

          sisetup
          round-mode=places,
          round-precision=3


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



          begindocument

          beginpycode
          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')
          endpycode

          A root of $f$ is pyNumop.newton(f,-2).


          begincenter
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,axis lines=center]
          addplot[black] table file.dat;
          endaxis
          endtikzpicture
          endcenter

          enddocument


          output2



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



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          pgfplotssetcompat=1.15

          begindocument

          beginpycode
          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)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[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);
          endaxis
          endtikzpicture
          endpysub


          enddocument


          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.






          share|improve this answer




















          • 7





            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






          • 1





            @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






          • 1





            @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

            – student
            Oct 24 '17 at 10:45















          51














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



          Here is a simple example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          begindocument

          beginpycode
          from sympy import *
          x = symbols('x')
          f = integrate(cos(x)*sin(x), x)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,title=!latex(f)]
          addplot[black] gnuplot !f;
          endaxis
          endtikzpicture
          endpysub

          enddocument


          enter image description here



          Here is another example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots
          usepackagesiunitx

          sisetup
          round-mode=places,
          round-precision=3


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



          begindocument

          beginpycode
          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')
          endpycode

          A root of $f$ is pyNumop.newton(f,-2).


          begincenter
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,axis lines=center]
          addplot[black] table file.dat;
          endaxis
          endtikzpicture
          endcenter

          enddocument


          output2



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



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          pgfplotssetcompat=1.15

          begindocument

          beginpycode
          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)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[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);
          endaxis
          endtikzpicture
          endpysub


          enddocument


          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.






          share|improve this answer




















          • 7





            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






          • 1





            @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






          • 1





            @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

            – student
            Oct 24 '17 at 10:45













          51












          51








          51







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



          Here is a simple example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          begindocument

          beginpycode
          from sympy import *
          x = symbols('x')
          f = integrate(cos(x)*sin(x), x)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,title=!latex(f)]
          addplot[black] gnuplot !f;
          endaxis
          endtikzpicture
          endpysub

          enddocument


          enter image description here



          Here is another example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots
          usepackagesiunitx

          sisetup
          round-mode=places,
          round-precision=3


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



          begindocument

          beginpycode
          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')
          endpycode

          A root of $f$ is pyNumop.newton(f,-2).


          begincenter
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,axis lines=center]
          addplot[black] table file.dat;
          endaxis
          endtikzpicture
          endcenter

          enddocument


          output2



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



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          pgfplotssetcompat=1.15

          begindocument

          beginpycode
          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)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[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);
          endaxis
          endtikzpicture
          endpysub


          enddocument


          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.






          share|improve this answer















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



          Here is a simple example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          begindocument

          beginpycode
          from sympy import *
          x = symbols('x')
          f = integrate(cos(x)*sin(x), x)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,title=!latex(f)]
          addplot[black] gnuplot !f;
          endaxis
          endtikzpicture
          endpysub

          enddocument


          enter image description here



          Here is another example:



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots
          usepackagesiunitx

          sisetup
          round-mode=places,
          round-precision=3


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



          begindocument

          beginpycode
          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')
          endpycode

          A root of $f$ is pyNumop.newton(f,-2).


          begincenter
          begintikzpicture
          beginaxis[xlabel=$x$,ylabel=$y$,samples=200,no markers,axis lines=center]
          addplot[black] table file.dat;
          endaxis
          endtikzpicture
          endcenter

          enddocument


          output2



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



          documentclassarticle

          usepackage[gobble=auto]pythontex
          usepackagepgfplots

          pgfplotssetcompat=1.15

          begindocument

          beginpycode
          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)
          endpycode


          beginpysub
          begintikzpicture
          beginaxis[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);
          endaxis
          endtikzpicture
          endpysub


          enddocument


          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.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Oct 21 '17 at 9:18

























          answered Oct 20 '17 at 20:39









          studentstudent

          12.4k24102176




          12.4k24102176







          • 7





            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






          • 1





            @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






          • 1





            @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

            – student
            Oct 24 '17 at 10:45












          • 7





            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






          • 1





            @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






          • 1





            @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

            – student
            Oct 24 '17 at 10:45







          7




          7





          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





          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






          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





          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




          1




          1





          @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





          @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




          1




          1





          @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

          – student
          Oct 24 '17 at 10:45





          @Ooker: zverovich.net/2016/05/13/giving-up-on-julia.html

          – student
          Oct 24 '17 at 10:45











          21














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



          • "Numerical methods with LuaLaTeX", by Juan Montijano, Mario Pérez, Luis Rández and Juan Luis Varona. TUGboat issue 35.1: https://www.tug.org/TUGboat/tb35-1/tb109montijano.pdf


          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.






          share|improve this answer





























            21














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



            • "Numerical methods with LuaLaTeX", by Juan Montijano, Mario Pérez, Luis Rández and Juan Luis Varona. TUGboat issue 35.1: https://www.tug.org/TUGboat/tb35-1/tb109montijano.pdf


            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.






            share|improve this answer



























              21












              21








              21







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



              • "Numerical methods with LuaLaTeX", by Juan Montijano, Mario Pérez, Luis Rández and Juan Luis Varona. TUGboat issue 35.1: https://www.tug.org/TUGboat/tb35-1/tb109montijano.pdf


              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.






              share|improve this answer















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



              • "Numerical methods with LuaLaTeX", by Juan Montijano, Mario Pérez, Luis Rández and Juan Luis Varona. TUGboat issue 35.1: https://www.tug.org/TUGboat/tb35-1/tb109montijano.pdf


              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 21 '17 at 9:25

























              answered Oct 20 '17 at 17:22









              Torbjørn T.Torbjørn T.

              158k13256445




              158k13256445





















                  12














                  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.)



                  documentclassscrartcl
                  usepackageluamplib
                  mplibtextextlabelenable
                  mplibsetformatmetafun
                  mplibnumbersystemdouble
                  begindocument
                  beginmplibcode
                  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;
                  endmplibcode
                  enddocument


                  enter image description here






                  share|improve this answer





























                    12














                    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.)



                    documentclassscrartcl
                    usepackageluamplib
                    mplibtextextlabelenable
                    mplibsetformatmetafun
                    mplibnumbersystemdouble
                    begindocument
                    beginmplibcode
                    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;
                    endmplibcode
                    enddocument


                    enter image description here






                    share|improve this answer



























                      12












                      12








                      12







                      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.)



                      documentclassscrartcl
                      usepackageluamplib
                      mplibtextextlabelenable
                      mplibsetformatmetafun
                      mplibnumbersystemdouble
                      begindocument
                      beginmplibcode
                      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;
                      endmplibcode
                      enddocument


                      enter image description here






                      share|improve this answer















                      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.)



                      documentclassscrartcl
                      usepackageluamplib
                      mplibtextextlabelenable
                      mplibsetformatmetafun
                      mplibnumbersystemdouble
                      begindocument
                      beginmplibcode
                      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;
                      endmplibcode
                      enddocument


                      enter image description here







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 21 '17 at 9:38

























                      answered Oct 20 '17 at 19:10









                      Franck PastorFranck Pastor

                      15.8k13760




                      15.8k13760





















                          6














                          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.






                          share|improve this answer



























                            6














                            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.






                            share|improve this answer

























                              6












                              6








                              6







                              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.






                              share|improve this answer













                              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.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Oct 22 '17 at 20:44









                              DJPDJP

                              7,93921732




                              7,93921732





















                                  5














                                  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.






                                  share|improve this answer



























                                    5














                                    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.






                                    share|improve this answer

























                                      5












                                      5








                                      5







                                      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.






                                      share|improve this answer













                                      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.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 20 '17 at 17:42









                                      jonaslbjonaslb

                                      613




                                      613



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to TeX - LaTeX Stack Exchange!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f397234%2fhow-to-do-mathematical-programming-in-latex%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          How should I use the fbox command correctly to avoid producing a Bad Box message?How to put a long piece of text in a box?How to specify height and width of fboxIs there an arrayrulecolor-like command to change the rule color of fbox?What is the command to highlight bad boxes in pdf?Why does fbox sometimes place the box *over* the graphic image?how to put the text in the boxHow to create command for a box where text inside the box can automatically adjust?how can I make an fbox like command with certain color, shape and width of border?how to use fbox in align modeFbox increase the spacing between the box and it content (inner margin)how to change the box height of an equationWhat is the use of the hbox in a newcommand command?

                                          Doxepinum Nexus interni Notae | Tabula navigationis3158DB01142WHOa682390"Structural Analysis of the Histamine H1 Receptor""Transdermal and Topical Drug Administration in the Treatment of Pain""Antidepressants as antipruritic agents: A review"

                                          inputenc: Unicode character … not set up for use with LaTeX The Next CEO of Stack OverflowEntering Unicode characters in LaTeXHow to solve the `Package inputenc Error: Unicode char not set up for use with LaTeX` problem?solve “Unicode char is not set up for use with LaTeX” without special handling of every new interesting UTF-8 characterPackage inputenc Error: Unicode character ² (U+B2)(inputenc) not set up for use with LaTeX. acroI2C[I²C]package inputenc error unicode char (u + 190) not set up for use with latexPackage inputenc Error: Unicode char u8:′ not set up for use with LaTeX. 3′inputenc Error: Unicode char u8: not set up for use with LaTeX with G-BriefPackage Inputenc Error: Unicode char u8: not set up for use with LaTeXPackage inputenc Error: Unicode char ́ (U+301)(inputenc) not set up for use with LaTeX. includePackage inputenc Error: Unicode char ̂ (U+302)(inputenc) not set up for use with LaTeX. … $widehatleft (OA,AA' right )$Package inputenc Error: Unicode char â„¡ (U+2121)(inputenc) not set up for use with LaTeX. printbibliography[heading=bibintoc]Package inputenc Error: Unicode char − (U+2212)(inputenc) not set up for use with LaTeXPackage inputenc Error: Unicode character α (U+3B1) not set up for use with LaTeXPackage inputenc Error: Unicode characterError: ! Package inputenc Error: Unicode char ⊘ (U+2298)(inputenc) not set up for use with LaTeX