• LaTeX environment to write verbatim Python code to an external file
    by Colas on October 11, 2025 at 9:39 am

    I’d like to have a solution environment that does the following: It writes the contents of the environment to an external file \jobname.py. All the solutions should be in the same file \jobname.py. The content of this environment (the solution) will be Python code and will include # characters and tab characters. The solution should not be displayed in the PDF, it should only be written in the external file. (If writing actual tab characters isn’t possible, I can work around it by replacing tabs with consecutive spaces.) Before writing the environment’s contents to \jobname.py, it should before write in \jobname.py the following line: ## Exercise \numberExercise, where \numberExercise is a macro that returns the exercise number (I will define this macro, but for testing you can assume \def\numberExercise{2.1}). The goal of this environment is to put directly the solutions to the exercises in my LaTeX document and to be able to create a .py file from the .tex document. I tried to write this environment but couldn’t get it to work. Could you help me? Please feel free to ask if anything is unclear. Here is a MWE: \documentclass{article} \def\numberExercise{2.1} \newenvironment{solution} {...} {...} \begin{document} Write a function \texttt{facto(n)} that returns the factorial of $n$. \begin{solution} # We proceed recursively def facto(n): if n == 0: return 1 else: return facto(n-1)*n \end{solution} \end{document}

  • Undesirable slant in ylabel in pgfplots
    by Scholar on October 11, 2025 at 3:20 am

    I am trying to plot multiple curves, of which some are trigonometric, on the same plot. However, the ylabel appears to be slanted every time I use trig format=rad in my code. If I remove this, everything works fine and the label appears the way I expect it to (standard ylabel). Here is the MWE. Any help leading to a fix is highly appreciated. \documentclass{article} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \usepackage{geometry} \begin{document} \begin{tikzpicture} \begin{axis}[ trig format=rad, ylabel={This is a test label}, xlabel={$t$ (s)}, grid=both, axis lines=box, xmin=0, xmax=20, ] \addplot [blue, thick, domain=0:20, samples=100] {2*(1-cos(x))}; \end{axis} \end{tikzpicture}

  • Headers like Knuth's TAOCP with fancyhdr
    by ncant on October 9, 2025 at 8:09 pm

    I would like to replicate the chapter and section headings as they appear in Knuth's The Art of Computer Programming (TAOCP). Here's a picture of two pages containing these headings (sorry I can't provide a scanned image): Where: 'COMBINATIONAL SEARCHING' is the chapter title and 'GENERATING ALL TREES' is the subsection title. (When writing a document in LaTeX using the 'book' class, the section and subsection headings swap out accordingly.) My goal is to implement this scheme using the fancyhdr package. Thanks to Knuth's taocpmac.tex file, containing all the macros he uses for TAOCP, I got the various text sizes working (CM10 for the chapter, section and page numbers, and CM8 for the chapter and section titles). However, I don't know how to space and align these elements accordingly. Here's a MWE with the code I wrote so far: \documentclass{book} \usepackage{fancyhdr} \pagestyle{fancy} \renewcommand{\chaptermark}[1]% {\markboth{\MakeUppercase{\thechapter.\ {\footnotesize#1}}}{}} \renewcommand{\sectionmark}[1]% {\markright{\MakeUppercase{\thesection.\ {\footnotesize#1}}}} \renewcommand{\headrulewidth}{0pt} \renewcommand{\footrulewidth}{0pt} \fancyhf{} \fancyhead[LE,RO]{\thepage} \fancyhead[LO]{\rightmark} \fancyhead[RE]{\leftmark} \usepackage{lipsum} \begin{document} \chapter{Test Chapter} \lipsum \section{Test Section} \lipsum \end{document} Can you help me?

  • tessellating a surface using maxima/minima-aware orthogonal trajectories (query multiple poles)
    by Jasper on October 9, 2025 at 1:27 am

    I was trying to illustrate some superimposed ripples, but no matter how many samples I use, it does not capture the fine detail. Moreover, many more samples is impossible due to complexity and time. Is there a more effective way to tessellate this? I was thinking that gridlines could radiate from both poles, and maybe we could find orthogonal trajectories through them... \documentclass[ tikz ,border = 1cm ]{standalone} \usepackage{pgfplots} \pgfplotsset{compat = 1.18} \begin{document} \begin{tikzpicture} \begin{axis}[ view = {-65}{35} ,axis equal ,hide axis ] \addplot3[ surf, z buffer=sort, draw = black, domain=-5:5, domain y=-10:10, samples=21, samples y=40, variable=\u, variable y=\v, point meta = u ] ( u ,v ,{ sin((5*sqrt((u)^2+(v-5)^2)) r) / sqrt((u)^2+(v-5)^2) + sin((5*sqrt((u)^2+(v+5)^2)) r) / sqrt((u)^2+(v+5)^2) } ); \end{axis} \end{tikzpicture} \end{document}

  • Why definition of \sett@b was changed in plain.tex?
    by Igor Liferenko on October 8, 2025 at 7:22 am

    In the edition of TeXbook from 1991, \sett@b is defined this way: \def\sett@b{\ifx\next\+ \let\next=\relax % turn off \outerness \def\next{\afterassignment\s@tt@b\let\next}% \else\let\next=\s@tcols\fi\next} \def\s@tt@b{\let\next=\relax \us@false\m@ketabbox} In most recent edition - this way: \def\sett@b{\ifx\next\+\def\nxt{\afterassignment\s@tt@b\let\nxt}% \else\let\nxt=\s@tcols\fi \let\next=\relax \nxt} % turn off \outerness \def\s@tt@b{\let\nxt=\relax \us@false\m@ketabbox} Why this change? For consistency, the old and new version should contain the comment one more time: \def\sett@b{\ifx\next\+ \let\next=\relax % turn off \outerness \def\next{\afterassignment\s@tt@b\let\next}% \else\let\next=\s@tcols\fi\next} \def\s@tt@b{\let\next=\relax \us@false\m@ketabbox} % turn off \outerness \def\sett@b{\ifx\next\+\def\nxt{\afterassignment\s@tt@b\let\nxt}% \else\let\nxt=\s@tcols\fi \let\next=\relax \nxt} % turn off \outerness \def\s@tt@b{\let\nxt=\relax \us@false\m@ketabbox} % turn off \outerness

  • Adding a colormap to a solution curve of a vector field
    by Black Mild on October 7, 2025 at 8:29 pm

    Here the curve is drawn with a single color (red) It's easy to get the solution curve. The below figure is drawn in this app for y'=x^2+y^2-1, y(0)=1/2. As you can notice the color of the curve is varying from red (x<-1) to purple (-1<x<1) then to blue (x>1). It is not color set of the rainbow, so it is not synchronious to the Rainbow colormap. My question: How to add a given colormap (such as Rainbow) to a solution curve of a vector field? I guess this is a kind of popular, but can not find a way with Asymptote. I expect not only Asymptote code but also any others as TikZ, MetaPost, lua, etc. The code should be apply for any colormaps Please use my code here as MWE.

  • Kerning for function composition \circ f in math mode
    by hugomg on October 7, 2025 at 3:36 am

    I noticed that, in the many math fonts, the letter f looks asymmetrical when it is to the right of a binary operator. I think it is because the spacing is computed from the bottom tip of the f, instead of from the middle of the f. In the following example, the first row the f is to the left of the operator and looks fine. In the second row the f is to the right and looks like the space between the circle and the f is too wide. In the third row I kludged with a negative \! space before the f; it looks better but perhaps a bit too narrow. As mentioned, the best workaround I could find is to manually add a \! before every single f. Is there a more robust or accurate way to fix this? I presume I must not be the first one to run into this issue where the function composition operator looks wonky when one of the functions is named f... \documentclass{article} \begin{document} Hello $f \circ g$. Hello $g \circ f$. Hello $g \circ \! f$. \end{document}

  • Please help to make siunitx screen-reader friendly
    by Miloop on October 3, 2025 at 8:03 pm

    I have a large scientific manuscript that I am trying to make screen-reader friendly. In many places, I have written quantities such as \qty{32.5(12)}{\micro\gram\per\milli\litre} I am trying to "redefine" the siunitx macros so that when I use them, they automatically contain the alt text/actual text. I tried to take inspiration from this previous post: Can I redefine a command to contain itself?. Here is what I have attempted: \documentclass{article} \usepackage[separate-uncertainty=true, mode=text]{siunitx} \usepackage{accsupp} \let\oldmilli\milli%copying the \milli command into \oldmilli \renewcommand{\milli}{%renewing the \milli command \BeginAccSupp{ActualText="milli"}%Defining how I want to screen reader to read this. \OriginalMilli%Go back to using the old \milli \EndAccSupp{}% } \begin{document} \qty{32.5(12)}{\milli\gram\per\gram} \end{document} I tried to experiment with \milli first and then proceed to other units, but already I run into this issue: ! LaTeX Error: Command \milli undefined. See the LaTeX manual or LaTeX Companion for explanation. Type H <return> for immediate help. Why does LaTeX say this is undefined when siunitx has already defined this for us? I know I can simply rewrite this code as: \documentclass{article} \usepackage[separate-uncertainty=true, mode=text]{siunitx} \usepackage{accsupp} \begin{document} \BeginAccSupp{ActualText="Thirty two point five plus minus one point two milli gram per gram"} \qty{32.5(12)}{\milli\gram\per\gram} \EndAccSupp{} \end{document} But doing this for the hundreds of quantities noted in the manuscript is simply impractical. Any suggestions? I'm not a power user, so please consider that when you give your suggestion. P.S: I am using pdfTeX as that's what I have learnt and used for many years. Current version is: pdfTeX 3.141592653-2.6-1.40.28 (TeX Live 2025) Siunitx version is 2025-05-17 v3.4.11 accsupp package version is 2019/12/05 v0.6

  • Use AntykwaTorunska with unicode math
    by HerpDerpington on October 3, 2025 at 7:06 pm

    I wanted to add the AntykwaTorunska font as a math version to my document which uses unicode math. However, it seems that the corresponding otf file does not define a math table, meaning that this won't work. There is however the anttor package, which allows to use the font as a math font. But this is also not unicode-math compatible: \documentclass{article} \usepackage[math]{anttor} \usepackage{fontspec} \usepackage{unicode-math} \begin{document} \[ \hat{A}_T = \sqrt{\xi}_Z x \] \end{document} becomes Commenting out \usepackage{unicode-math} resolves this again. What are my options here so that I can use this font as a math font? I think this problem can be gerneralized to many other fonts as well.

  • Unable to use booktabs with longtblr
    by SaltySeaDog on October 2, 2025 at 12:37 pm

    I've been trying to type set a mark scheme using longtblr from tabulararray but I'm running into what I can only describe as a brick wall. I want to force the page breaks to only happen at after the complete question and a line between sub parts \documentclass{article} \usepackage{tabularray} \UseTblrLibrary{booktabs} \newcommand{\pbreak}{\nopagebreak\midrule} % Break between parts of a solution \newcommand{\sbreak}{\nopagebreak\midrule} % Breaks between 1a and 1b for example, not allow page breaks \newcommand{\qbreak}{\midrule} % Breaks between questions, allow page breaks \begin{document} \begin{longtblr}{ colspec={l c Q[l]}, width=\linewidth } \toprule Q & Part & Marks \\ \midrule 1 & a & comments \\ \sbreak 1 & b & more comments \\ \qbreak 2 & & question with multi line problems \\ \pbreak & & more working here as well \\ \qbreak 3 & & another question with multi line problems \\ \pbreak & & more working here as well \\ \bottomrule \end{longtblr} \end{document} I would expect this to look like: ================================================== Q Part Marks -------------------------------------------------- 1 a comments -------------------------------------------------- 1 b more comments -------------------------------------------------- 2 question with multi line problems more working here as well -------------------------------------------------- 3 another question with multi line problems more working here as well ================================================== But instead I get this which is nothing like what I would expect.

  • Draw two strands that twist around each other in Tikz
    by Laut567 on September 30, 2025 at 4:31 pm

    Using the approach described here : https://texblog.org/2014/04/28/simple-dna-protein-interaction-model-with-tikz/ \documentclass[border=10pt]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.pathmorphing} \begin{document} \begin{tikzpicture}[ decoration={coil}, dna/.style={ decorate, thick, decoration={ aspect=0, segment length=0.5cm } } ] % DNA strands \draw[dna, decoration={amplitude=.15cm}] (.1,0) -- (4.85,0); \draw[dna, gray, decoration={amplitude=-.15cm}] (0,0) -- ++(4.75,0); \end{tikzpicture} \end{document} which gives I would like the two strands to twist around each other, alternating above and below, like this : I tried to play with knots without success.

  • Why is \l_keys_choice_tl a token list instead of a string variable?
    by User23456234 on September 29, 2025 at 6:39 am

    Question: Why is \l_keys_choice_tl in l3keys a tl instead of a str variable? My understanding is that key names are stored as strings using \tl_to_str:n. For choice keys, each choice is implemented as just another key. e.g. \keys_define:nn { module } { key .choices:nn = { one , two } { <code> } } defines the keys module/key/one and module/key/two. For example, the following code: \documentclass{article} \ExplSyntaxOn \debug_on:n { all } \str_new:N \l_module_name_str \keys_define:nn { module } { key .choices:nn = { one , two } { \str_set:Nn \l_module_name_str {#1} } } \ExplSyntaxOff \begin{document} text \end{document} generates the following in the .log file: Defining key module/key on line 11 Defining key module/key/unknown on line 11 Defining key module/key/one on line 11 Defining key module/key/two on line 11 Since the selected choice of a choice key is treated as a string, then shouldn't the variable that stores the selected choice also be a string?

  • What changed between the final TeXLive 2023 and the final TeXLive 2024 concerning an lstlisting inside a TikZ node?
    by AlMa1r on September 28, 2025 at 6:28 pm

    Feeding \documentclass{article} \usepackage{listings} \usepackage{tikz} \begin{document} \begin{tikzpicture} \node {% \begin{lstlisting} foo \end{lstlisting}}; \end{tikzpicture} \end{document} to latex or pdflatex works just fine in the final TeX Live 2023 (and prior versions probably, dating back to 2014 or 2015). However, an error is reported in the final TeX Live 2024, or when the TeX Live 2025 packages in Debian stable as of 2025-09-28 are used; the console shows this: ! Package tikz Error: Giving up on this path. Did you forget a semicolon?. See the tikz package documentation for explanation. Type H <return> for immediate help. ... l.9 \end{lstlisting}} ; ? H This error message was generated by an \errmessage command, so I can't give any explicit help. Pretend that you're Hercule Poirot: Examine all clues, and deduce the truth by order and method. ? The documentation of tikz shown by texdoc tikz does not mention lstlisting. In this regard, what changed between the final TeX Live 2023 and the final TeX Live 2024 in plain terms, and what were the reasons for the change? (The output of colordiff -b -C1 TEXDIR/2023/texmf-dist/tex/latex/listings/listings.sty TEXDIR/2024/texmf-dist/tex/latex/listings/listings.sty doesn't tell me much; the maintainer of listings has been informed.) How to put an lstlisting into a tikz node these days? For the purpose of the last question, we can assume that the content of the lstlisting contains plain text including new lines but no escapes. So far, I've been able to come up with bulky \documentclass{article} \pagestyle{empty} \usepackage{listings} \usepackage{tikz} \newsavebox{\codebox} \begin{document} \begin{lrbox}{\codebox}% \begin{lstlisting} foo \end{lstlisting}% \end{lrbox} \begin{tikzpicture} \node[draw,inner sep=0pt] {\usebox{\codebox}}; \end{tikzpicture} \end{document} and, probably equivalently (?), \documentclass{article} \pagestyle{empty} \usepackage{listings} \usepackage{tikz} \newbox\codebox \begin{document} \setbox\codebox=\hbox{% \begin{lstlisting} foo \end{lstlisting}} \begin{tikzpicture} \node[draw,inner sep=0pt] {\box\codebox}; \end{tikzpicture} \end{document} where I added the draw and inner sep options for clarity. Though both “boxy” solutions generate the required without errors, the workarounds are cumbersome, and there is some superfluous vertical spacing inside the frame. A direct, easier solution would be very much welcome. (If this plays any role, my nonminimal confidential example is a C++ snippet (without escapes) inside lstlisting inside \node {…} of tikzpicture inside minipage inside figure[t] inside example of llncs.) The tikz team has been informed in http://github.com/pgf-tikz/pgf/issues/1420 . Edit by cfr Comparative file listing, where the 2023 version compiles, but the 2024 does not. Both are vanilla TeX Live. < LaTeX2e <2023-11-01> patch level 1 < L3 programming layer <2024-02-20> --- > LaTeX2e <2024-11-01> patch level 2 > L3 programming layer <2025-01-18> 435,437c448,450 < article.cls 2023/05/17 v1.4n Standard LaTeX document class < size10.clo 2023/05/17 v1.4n Standard LaTeX file (size option) < listings.sty 2024/02/21 1.10 (Carsten Heinz) --- > article.cls 2024/06/29 v1.4n Standard LaTeX document class > size10.clo 2024/06/29 v1.4n Standard LaTeX file (size option) > listings.sty 2024/09/23 1.10c (Carsten Heinz) 439,441c452,454 < lstpatch.sty 2024/02/21 1.10 (Carsten Heinz) < lstmisc.sty 2024/02/21 1.10 (Carsten Heinz) < listings.cfg 2024/02/21 1.10 listings configuration --- > lstpatch.sty 2024/09/23 1.10c (Carsten Heinz) > lstmisc.sty 2024/09/23 1.10c (Carsten Heinz) > listings.cfg 2024/09/23 1.10c listings configuration 448,449c461,462 < graphics.sty 2022/03/10 v1.4e Standard LaTeX Graphics (DPC,SPQR) < trig.sty 2021/08/11 v1.11 sin cos tan (DPC) --- > graphics.sty 2024/08/06 v1.4g Standard LaTeX Graphics (DPC,SPQR) > trig.sty 2023/12/02 v1.11 sin cos tan (DPC) 451c464 < pdftex.def 2022/09/22 v1.2b Graphics/color driver for pdftex --- > pdftex.def 2024/04/13 v1.2c Graphics/color driver for pdftex 456c469 < xcolor.sty 2023/11/15 v3.01 LaTeX color extensions (UK) --- > xcolor.sty 2024/09/29 v3.02 LaTeX color extensions (UK) 469c482 < l3backend-pdftex.def 2024-02-20 L3 backend support: PDF output (pdfTeX) --- > l3backend-pdftex.def 2024-05-08 L3 backend support: PDF output (pdfTeX)

  • How to sample curves more densely (by arc-length) when their trajectory is more volatile, and less so when the trajectory is more constant
    by Jasper on September 27, 2025 at 6:12 pm

    I have a curve which has significant changes in its trajectory in some parts of its domain, while its trajectory remains relatively constant in others. I would like a way to sample this curve on a domain, where the samples are more densely collected when the curve's trajectory is more volatile, and less densely when the curve's trajectory is less volatile. I should clarify what I mean by density of samples too; by density, I mean the arc-length distance between the points being less - I do not mean by density the distance on their x-components. The motivation for this was me needing to use extraordinary amounts of samples for curves which only required them in localized places - essentially wasting a large portion of my computer's efforts. I have developed a technique which samples curves more densely when the magnitude of their second derivative is greater, but it has a couple of problems: My technique solves it like an initial-point problem, so I have no way of determining the number of samples needed to cover my desired domain. (In fact, the endpoint of the curve will almost always not coincide with a point in the sequence of samples, though it will always be close to a sample.) While the curve seems to be well-samples leading up to maxima and minima, it seems to degrade substantially just after the maxima/minima, making the resolution bad for the part immediately following the maxima/minima. I was hoping that someone could answer this with a technique that can sample curves in such a way that the samples are a larger arc-length apart (to a maximum) when the second derivative is small, and closer together when it is larger. In particular, I would like a way to specify the domain, so enough samples are chosen to fill it exactly. There should also be a way to set the desired "resolution" (by resolution I mean the parameter which affects the global sampling density). \documentclass[ tikz ,border = 1cm ]{standalone} \usetikzlibrary{arrows.meta} \begin{document} \pgfmathsetmacro{\samples}{140} \pgfmathsetmacro{\resolution}{0.5} \begin{tikzpicture}[ declare function ={ f(\x) = sin((e^(\x*(3-\x))) r) + 2.5*(atan(2*\x-7)/180*pi + pi/2) ; df(\x) = cos((e^(\x*(3-\x))) r) * e^(\x*(3-\x)) * (3-2*\x) + 2.5/((2*\x-7)^2 + 1) ; norm(\x,\y) = sqrt((\x)^2+(\y)^2); asinh(\x) = ln(\x+sqrt((\x)^2+1)); } ] \draw[ domain = -2:10 ,samples = 1000 ,{-Circle[red]} ] plot (\x,{f(\x)}); \pgfmathsetmacro{\R}{0.03} \pgfmathsetmacro{\startx}{-2} \pgfmathsetmacro{\starty}{f(\startx)} \foreach \t[ remember = \newx as \x (initially \startx) ,remember = \newy as \y (initially \starty) ,parse = true ] in {0,...,\samples} { \pgfmathsetmacro{\dy}{df(\x)} \pgfmathsetmacro{\ddy}{(df(\x+0.001)-\dy)/0.001} \pgfmathsetmacro{\dx}{ \resolution/norm(1,\dy)) / (asinh(abs(\ddy))+1) } \pgfmathsetmacro{\newx}{\x+\dx} \pgfmathsetmacro{\newy}{f(\x+\dx)} \fill (\x,\y) circle[radius = \R]; %\draw (\x,\y) -- (\newx,\newy); \pgfmathparse{\t == \samples} \ifnum\pgfmathresult=1 \fill[green] (\newx,\newy) circle[radius = \R+0.03]; \fi } \end{tikzpicture} \end{document}

  • Fix integral lower bound kerning in textstyle or smaller with unicode-math
    by HerpDerpington on September 26, 2025 at 9:58 pm

    When using unicode math, the lower bound of the integrals is very close to the integral symbol, see this example \documentclass{article} \usepackage{unicode-math} \begin{document} Lorem ipsum $\int_0^1x^{\int_0^1}$ \[\int_0^1\] \end{document} which becomes This becomes even more noticeable when zooming out. So, can I automatically add a small kern before the lower bound whenever text style or smaller is used?

  • Traversing a curve by portions of its arclength
    by Jasper on September 26, 2025 at 9:21 pm

    How can you traverse a cosine wave by portions of its arclength, rather than by just the normal parametric equation? When I plot points from an evenly partitioned domain line, what happens is some are close together when the slope is flat, and then they are further apart when the slope is less flat. How can I traverse the wave so that the points are all the same arclength apart? It might not be very useful for all applications, but it seems like a fundamental thing to want to be able to do.

  • How Create a math symbol
    by Viśvāmitra on September 25, 2025 at 7:02 pm

    I created the following symbol, however it doesn't work well in all math environments. How to create this so that it adjust meaningfully with respect to size in various math environments, and also works well with commands like $\big\coexist$. \newcommand{\coexist}[1][]{\hspace{.15em}\raisebox{-.35em}{ \begin{tikzpicture}[scale=0.15]\draw[line width=0.5pt] (-.85,-0.2) -- (-1,0) -- (0.15,1.5);\draw[line width=0.5pt] (-0.45,-0.65) -- (0.15,-1.5);\draw[line width=0.5pt] (-1.15,1.5) -- (-0.55,0.65);\draw[line width=0.5pt] (-1.15,-1.5) -- (0,0) -- (-0.15,0.2); \end{tikzpicture} }\hspace{.15em}} Here is the symbol in use for: $\langle \coexist\rangle$

  • How much does tagging affect my compilation?
    by Teepeemm on September 24, 2025 at 6:27 pm

    I have a tex project where I want to tag the output. It seems like tagging makes the compilation take longer. How much longer? What else is affected by tagging?

  • Plotting functions without sampling artefacts
    by arctiq on September 24, 2025 at 3:28 pm

    I am interested in a generic technique to visualize functions in a quality appropriate for journal articles. Consider the function $$-\sqrt{\lvert x-\tan y \rvert}$$ over $[0,1]^2$. Tools like WolframAlpha can plot it beautifully with Plot3D[-Sqrt[Abs[x - Tan[y]]], {x, 0, 1}, {y, 0, 1}]: However, PGFplots produces unacceptable artefacts: \documentclass[border=10pt]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.18} \begin{document} \begin{tikzpicture} \begin{axis}[view={30}{30}, domain=0:1] % Unacceptable plot of the desired function \addplot3[surf,shader=faceted interp]{-sqrt(abs(x-tan(deg(y))))}; % Desired shape of the ridge \addplot3[domain=0:pi/4, samples y=0] ({tan(deg(x))},{x},{0}); \end{axis} \end{tikzpicture} \end{document} Increasing the number of samples does not help as the slope approaches infinity near the $x=\tan y$ singularity. Postprocessing will not help as the sampling loses information. The black curve indicates the correct shape and position of the ridge compared to the actual result. I run into this all the time and know of no solution except drawing it by hand. Solutions involving external tools and LuaLaTeX are acceptable. GNUplot can not handle this either. I was unable to find a solution in the PGFplots documentation. AI tools provide no help either.

  • Why is my Student's t distribution plotting incorrectly in pgfplots?
    by lane-h-rogers on September 22, 2025 at 10:45 pm

    I am trying to plot a Student's t distribution without using gnuplot. Here is what I have been trying: \documentclass{standalone} \usepackage{tikz} \usepackage{pgfplots} \begin{document} \pgfmathdeclarefunction{gamma}{0}{% \pgfmathparse{sqrt(2*pi*x)*(x/e)^(x)} % *exp(1/(12*x)) } \pgfmathdeclarefunction{tdist}{1}{% \pgfmathparse{(gamma(#1/2 + 1/2)/(sqrt(#1*pi)*gamma(#1/2)))*((1 + (x^2)/#1)^(-#1/2 - 1/2))} % #1 is df } \begin{tikzpicture} \begin{axis}[ thick, no markers, domain=-10:10, samples=400, axis x line*=bottom, axis y line*=middle, x axis line style={draw opacity=100,color=blue}, y axis line style={draw opacity=100,color=blue}, xlabel=$t_{8}$, ylabel=$P(x)$, every axis y label/.style={at=(current axis.above origin),anchor=south}, every axis x label/.style={at=(current axis.right of origin),anchor=west}, height=4cm, width=8cm, xtick={0}, xticklabels={$\mu=0$}, ytick={1}, enlargelimits=false, clip=false, axis on top, grid = major ] \addplot{tdist(8)}; \end{axis} \end{tikzpicture} \end{document} This yields the plot: which is clearly not correct, as a t distribution should have a peak with height roughly P(x) = .4. I have already checked the formula many times and cannot find an error. Does anyone have an idea of what is going wrong? Is it possibly due to the imprecision inherent in Stirling's approximation of the gamma function?

  • How can I draw this box in 3D ? I am unhappy with that I have
    by Shyamhs on September 22, 2025 at 12:57 am

    I need to draw a 3D box comprising two half cylinders on either side attached to a cuboid with square holes. I have managed to accomplish this. But I am not happy with what I have now. For one, it does not look like a 3D picture. I would appreciate any pointers on a better version \documentclass[a4paper,12pt]{article} \usepackage{tikz} \usepackage{tikz-3dplot} \begin{document} \tdplotsetmaincoords{40}{20} \tdplotsetrotatedcoords{0}{15}{21} \begin{tikzpicture}[scale=0.85,tdplot_rotated_coords] % Draw the semicircle (opening to the left) \draw[very thick] (0,-1.5) arc (90:-90:-1.5); % Draw the semicircle for right semicircle (opening to the right) \draw[very thick] (4,1.5) arc (90:-90:1.5); % draw top and bottom lines connecting the two semicircles \draw[very thick] (0,1.5) -- (4,1.5); \draw[very thick] (0,-1.5) -- (4,-1.5); % Draw the below quarter circle (opening to the left) \draw[very thick] (0,-5.5) arc (90:0:-1.5); % Draw the below quarter circle (opening to the right) \draw[very thick] (5.5,-4) arc (0:-90:1.5); % draw bottom line connecting the two semicircles \draw[very thick] (0,-5.5) -- (4,-5.5); % Draw the left vertical line connecting the left upper % semicircle and the left lower quarter circle \draw[very thick] (-1.5,0) -- (-1.5,-4); % Draw the right vertical line connecting the right upper % semicircle and the right lower quarter circle \draw[very thick] (5.5,0) -- (5.5,-4); \draw[very thick,rotate=-9] (0,-3.5) rectangle (1,-2.5); \draw[very thick,rotate=-9] (1.5,-3.25) rectangle (2.5,-2.25); \draw[very thick,rotate=-9] (3,-3) rectangle (4,-2); \draw[very thick,rotate=-9] (4.5,-2.75) rectangle (5.5,-1.75); \end{tikzpicture} \end{document}

  • How to typeset the complete structure of deeply nested formulas?
    by MaxD on September 19, 2025 at 2:25 pm

    I have some formulas with a deeply nested structure that I would like to typeset combined in a single setting, similar to the following graphic I made in Paint. There are multiple nested subexpressions (a, b, c, d, e). The ability to use multiple lines per expression, as well as the ability to place comments or equation numbers on the right would both be really nice as well. I just found and started using the dirtree package which works fine for many things, but it can't do the reversed tree structure I need in this particular case. How else could I do this? \documentclass{article} \begin{document} a = 1 + 2 + 3 + 4 + 5 + 6 + 7 b = 8 + 9 + 10 + 11 + 12 + 13 c = a + b + 14 + 15 + 16 d = 17 + 18 + 19 + 20 + 21 e = d + 22 + 23 + 24 + 25 + 26 + 27 + 28 + 29 + 30 + 31 + 32 f = c + e + 33 + 34 + 35 \end{document}

  • An enumeration with apostrophes
    by Leandro Caniglia on September 17, 2025 at 11:31 pm

    I'm trying to set up an enumeration that would produce two items P_3' and P_3''. My attempt \usepackage[shortlabels]{enumitem} \newcommand{\apostrophes}[1]{% \ifcase\numexpr#1\relax \or ' \or '' \or ''' \or '''' \or '''''% \else '''''\fi} \begin{enumerate}[label={p$_3$\apostrophes{\arabic*}},font=\scshape] \item \label{P3'} \item \label{P3''} \end{enumerate} so that I can then refer to the items with \newcommand{\Ptprime}{{\upshape\textsc{\ref{P3'}}}} \newcommand{\Ptdprime}{{\upshape\textsc{\ref{P3''}}}} However, I get a "missing number, treated as zero" error message. I've also tried \arabic{\value{enumi}}' and \arabic{\theenumi}' without luck (same error). How should I change my code, please? Compilable version \documentclass{article} \usepackage[shortlabels]{enumitem} \newcommand{\apostrophes}[1]{% \ifcase\numexpr#1\relax \or ' \or '' \or ''' \or '''' \or '''''% \else '''''\fi} \newcommand{\Ptprime}{{\upshape\textsc{\ref{P3'}}}} \newcommand{\Ptdprime}{{\upshape\textsc{\ref{P3''}}}} \begin{document} \begin{enumerate}[label={p$_3$\apostrophes{\arabic*}},font=\scshape] \item \label{P3'} There are four points in general position. \item \label{P3''} The incidence relation is not empty. \end{enumerate} The first item is number \Ptprime. The second item is number \Ptdprime. \end{document}

  • TikZ bounding box not calculated properly for rotated circle nodes in standalone class
    by TheFox on September 17, 2025 at 10:37 am

    I'm using tikz to create a figure with a ring and n nodes on it equally separated by an angle of 360° / n. Since I want the number of nodes to be arbitrary I defined a command which creates the tikzpicture: \newcommand{\drawfigure}[2]{% \def\n{#1} \begin{tikzpicture} \draw[dashed] (0,0) circle (\rring); \foreach \i in {0,...,\numexpr\n-1\relax}{ \pgfmathsetmacro{\angle}{360*\i/\n} \begin{scope}[shift={(\angle:\rring)}, rotate=\angle] \draw[fill=black!20] #2; \end{scope} } \end{tikzpicture} } where \rring is defined globally, the first argument is the number of nodes to create and the second the node to draw. For example if one wants circular/rectangular nodes he can pass as second argument the macro \nodecirc/\noderect: \def\nodecirc{% (0,0) circle (\rnode); } \def\noderect{% (-\rnode,-\rnode) rectangle (\rnode,\rnode); } The problem I stumbled across is related to the bounding box of tikzpictures for specific values of n, and only with the circular node. For example for n = 3 I obtain a white space above the upper node, but not below the lower one as in this picture (sorry for the white backgrounds, if I added a background color the bounding box would get bigger, just open the image in a new tab): a similar problem arises for n = 5: but not for n = 4: while as I said with the rectangular node everything works fine. The issue persists if I set the bounding box as \usetikzlibrary{bbox} \tikzset{% bezier bounding box } the only difference being now some nodes are cut off, for instance the lower one in the case n = 3: Here is a MWE: \documentclass[tikz]{standalone} %\usetikzlibrary{bbox} \tikzset{% %bezier bounding box } \def\rring{1} \def\rnode{0.4} \def\nodecirc{% (0,0) circle (\rnode); } \def\noderect{% (-\rnode,-\rnode) rectangle (\rnode,\rnode); } \newcommand{\drawfigure}[2]{% \def\n{#1} \begin{tikzpicture} \draw[dashed] (0,0) circle (\rring); \foreach \i in {1,...,\n}{ \pgfmathsetmacro{\angle}{360*\i/\n} \begin{scope}[shift={(\angle:\rring)}, rotate=\angle] \draw[fill=black!20] #2; \end{scope} } \end{tikzpicture} } \begin{document} \drawfigure{3}{\nodecirc} \drawfigure{4}{\nodecirc} \drawfigure{5}{\nodecirc} \drawfigure{3}{\noderect} \drawfigure{4}{\noderect} \drawfigure{5}{\noderect} \end{document} How can I solve the problem, possibly without setting manually the bounding box? Why does tikz behave like this, it shouldn't since every node is placed symmetrically with respect to the origin? EDIT: as suggested by @gernot the problem seems to be related to how the bounding box of each node is calculated. See these examples: for n = 3, and for n = 5, while in the case n = 4 every bounding box is computed correctly. The bounding boxes were drawn replacing the scope environment with: \begin{scope}[shift={(\angle:\rring)}, rotate=\angle, local bounding box=bbox] \draw[fill=black!20] #2; \end{scope} \draw[red] (bbox.south west) rectangle (bbox.north east); Still I don't understand where's the problem, and why symmetric nodes don't have symmetric bounding boxes...

  • Drawing vertical and horizontal vectors along a Bézier curve (without local rotation)
    by lukewarn on September 16, 2025 at 10:26 pm

    I’m trying to annotate a quadratic Bézier* curve in TikZ with vectors. Right now I can draw normal vectors (red arrows) at multiple points along the curve using the decorations.markings library. Here is a minimal working example: \documentclass[tikz,border=5mm]{standalone} \usepackage{tikz} \usetikzlibrary{decorations.markings,calc,arrows.meta} % <-- arrows.meta added \begin{document} \begin{tikzpicture} % Quadratic Bézier control points \coordinate (QB1) at (0,0); \coordinate (QB2) at (0,3); \coordinate (QB3) at (8,3); % Convert quadratic to cubic control points \path let \p1 = (QB1), \p2 = (QB2), \p3 = (QB3), \p4 = ({(1/3)*\x1 + (2/3)*\x2},{(1/3)*\y1 + (2/3)*\y2}), \p5 = ({(2/3)*\x2 + (1/3)*\x3},{(2/3)*\y2 + (1/3)*\y3}) in coordinate (QB_aux1) at (\p4) coordinate (QB_aux2) at (\p5); % The curve \draw[thick,black] (QB1) .. controls (QB_aux1) and (QB_aux2) .. (QB3); % Normal vectors using arrows.meta syntax \draw[ postaction={ decorate, decoration={ markings, mark=between positions 0. and 1. step 0.1 with { \draw[color=red, -{Latex[length=1mm]}] (0,0) -- (0,0.5); } } } ] (QB1) .. controls (QB_aux1) and (QB_aux2) .. (QB3); \end{tikzpicture} \end{document} Now, in addition to the red arrows (normals), I would like to draw vertical and horizontal arrows at the same positions. However, it seems that TikZ rotates every arrow into the local coordinate system of the decoration. As a result, I cannot find a way to get all arrows to stay vertical/horizontal in the global picture. Also, I don’t want the red vectors to become the vectorial sum of the horizontal and vertical components — they are all independent drawings. Question: How can I place these vertical and horizontal arrows at each marked position along the Bézier curve, aligned with the global axes, rather than with the curve’s local frame? * For some reason, if I use \draw[thick,black] (QB1) .. controls (QB2) .. (QB3); instead of \draw[thick,black] (QB1) .. controls (QB_aux1) and (QB_aux2) .. (QB3); the curve doesn't look like a quadratic Bèzier.

  • Why can't I use \StrLeft for this macro?
    by haifisch123 on September 16, 2025 at 7:47 pm

    I'd like to have a macro which returns the first two letters of a weekday given a certain date (DD.MM.YYYY). For example "16.09.2025" would be "Tu". \documentclass{article} \usepackage{datetime} \usepackage{xstring} % input has the form "DD.MM.YYYY" % outputs first two letters of the weekday of a given date \newcommand{\strToWeekday}[1]{ \StrBefore{#1}{.}[\myDay]% \StrBehind{#1}{.}[\myYearAndMonth]% \StrBefore{\myYearAndMonth}{.}[\myMonth]% \StrBehind{\myYearAndMonth}{.}[\myYear]% \dayofweekname{\myDay}{\myMonth}{\myYear}[\myWeekday]% \StrLeft{\myWeekday}{2} } \begin{document} \strToWeekday{11.05.2023} % should return Th \strToWeekday{13.05.2023} % should return Sa \strToWeekday{16.09.2025} % should return Tu \end{document} Splitting the string, and getting (the long form of) the weekday works fine. But I couldn't manage to get only the first 2 letters of this longform. Thanks in advance for any help.

  • Defining a verbatim environment as a pair of commands (e.g., using c argspec), with optional argument
    by Karl Berry on September 16, 2025 at 4:55 pm

    I'm wondering if it's possible to use the new c arg spec (or any other method) in LaTeX to define a verbatim environment as a pair of commands. I also want the starting command to take an optional argument. My attempt, following the example in ltnews41, fails: \documentclass{article} \NewDocumentEnvironment{tubtyping}{!O{} c} {\begin{verbatim}#2 \end{verbatim} } {} \def\starttyping{\begin{tubtyping}} \def\stoptyping{\end{tubtyping}} \begin{document} \starttyping[foo] foo \stoptyping \starttyping bar \stoptyping \end{document} Not surprisingly, it gets the error Runaway argument? bar\obeyedline \stoptyping\obeyedline \end{document}\obeyedline \obeyedline \ET C. ! File ended while scanning use of \@xverbatim. I presume the verbatim environment can't recognize the \end{verbatim} since it's already been tokenized in the definition. I get similar errors with commands defined using traditional optional arguments (\newcommand\starttyping[1][]), etc., since (it seems) looking ahead for the [ freezes the tokens. I'm not worried about end of line behavior, having text on the \start or \stop lines, etc. It would just be helpful to have the basic idea work. This is with current (as of 2025-09-16) pdflatex-dev, LaTeX2e <2025-06-01> patch level 1 and L3 programming layer <2025-08-13>. I saw the previous question Defining a new environment extending a verbatim environment but it's not about L3. If anything in fancyvrb, listings, or any other verbatim package offers this functionality, I'd be happy to hear about it. I don't need to define it myself, I just couldn't find anything that provides it. P.S. I should mention, an alternative approach would be a way to change the end-verbatim string from \end{verbatim} to \stoptyping. Then \starttyping could take the optional arg and start the verbatim env, and the env could end normally. As far as I know the end-verbatim string cannot be changed, though.

  • How to draw the Ketamine molecular structure using ChemFig?
    by Marco Fanelli on September 16, 2025 at 11:27 am

    How to draw the Ketamine molecular structure using ChemFig? Question I'm trying to draw the molecular structure of Ketamine (C₁₃H₁₆ClNO) using the chemfig package in LaTeX. I'm having trouble properly positioning the substituents on the benzene ring and connecting the cyclohexanone ring. What I've tried Here's my current attempt: \documentclass{article} \usepackage{chemfig} \begin{document} \chemfig{*6(=-(-[:30](=[:90]O)-[:330]HN-[:30])=-(-Cl)=)} \end{document} Expected result

  • Vertical dashed lines in tikz. Figure from Proofs Without Words
    by Richard on September 16, 2025 at 9:08 am

    I’m trying to recreate a figure from Roger B. Nelsen’s Proofs Without Words: Exercises in Visual Thinking—specifically “Sums of Squares V” (Integer Sums, p. 81). My code gets everything right except the vertical dashed lines inside each unit square. Can these be drawn when using rectangle ++(1,1), or should I use a different approach? \documentclass[]{article} \usepackage [utf 8]{inputenc} \usepackage{soul} \usepackage {ulem} \usepackage{amsmath , bm} \usepackage{tikz} \usetikzlibrary{positioning} \usetikzlibrary{quotes,angles} \usetikzlibrary {arrows.meta} \usetikzlibrary{math} \usetikzlibrary {babel} \usetikzlibrary{calc} %for coordinate calc \usepackage{tikz,ifthen} \begin{document} \begin{tikzpicture}[x=1cm,y=1cm,yscale=-1] % neutralize \i and \j only within this block \begingroup \let\i\relax \let\j\relax %First rectangle \foreach \i in {-1} \foreach \j in {0} \draw (\i,\j) rectangle ++(1,1); %Second rectangle \foreach \i in {0,1}{ \foreach \j in {0,1}{ \ifnum\j=0\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else\ifnum\j=2\relax \else \draw (\i,\j) rectangle ++(1,1); \fi\fi } } %Third rectangle \foreach \i in {2,3,4}{ \foreach \j in {0,1,2}{ \ifnum\j=0\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else\ifnum\j=2\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else \draw (\i,\j) rectangle ++(1,1); \fi\fi } } %Fourth rectangle \foreach \i in {2,3,4}{ \foreach \j in {0,1,2}{ \ifnum\j=0\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else\ifnum\j=2\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else \draw (\i,\j) rectangle ++(1,1); \fi\fi } } %Fifth rectangle \foreach \i in {5,6,7,8}{ \foreach \j in {0,1,2,3}{ \ifnum\j=0\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else\ifnum\j=2\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else \draw (\i,\j) rectangle ++(1,1); \fi\fi } } %Sixth rectangle \foreach \i in {9,10,11,12,13}{ \foreach \j in {0,1,2,3,4}{ \ifnum\j=0\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else\ifnum\j=2\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else\ifnum\j=4\relax \filldraw[fill=gray!30,draw=black] (\i,\j) rectangle ++(1,1); \else \draw (\i,\j) rectangle ++(1,1); \fi\fi\fi } } \endgroup \end{tikzpicture} \end{document}

  • How to double chapter numbers and let hyperref do its work correctly
    by Christophe on September 15, 2025 at 9:40 am

    I have the following MWE with the goal to double some chapter numbers (don't ask me why, please). The problem is obviously that the links in the toc do not work anymore (hyperref). How to make these links work correctly? Or how should I do to double some chapter numbers? Thank you! \documentclass{memoir} \usepackage{hyperref} \begin{document} \tableofcontents \newpage \chapter{One} \section{First} Blabla. \section{Second} Blabla. \setcounter{chapter}{0} \chapter{One again} \section{Third} Blabla. \section{Fourth} Blabla. \end{document}