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
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
|
show 3 more comments
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
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 PSTrickspst-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
|
show 3 more comments
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
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
pgfmath
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 PSTrickspst-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
|
show 3 more comments
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 PSTrickspst-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
|
show 3 more comments
5 Answers
5
active
oldest
votes
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
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
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.
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
|
show 5 more comments
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.
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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
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.
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
|
show 5 more comments
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
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
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.
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
|
show 5 more comments
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
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
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.
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
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
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.
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
|
show 5 more comments
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
|
show 5 more comments
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.
add a comment |
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.
add a comment |
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.
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.
edited Oct 21 '17 at 9:25
answered Oct 20 '17 at 17:22
Torbjørn T.Torbjørn T.
158k13256445
158k13256445
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Oct 21 '17 at 9:38
answered Oct 20 '17 at 19:10
Franck PastorFranck Pastor
15.8k13760
15.8k13760
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Oct 22 '17 at 20:44
DJPDJP
7,93921732
7,93921732
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Oct 20 '17 at 17:42
jonaslbjonaslb
613
613
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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